Interface
객체가 어떤 속성과 메서드를 가져야 하는지 지정
interface labelValue {
size: number;
label: string;
}
function printLabel(labelObj: { label: labelValue }) {
console.log(labelObj.label);
}
let myObj: labelValue = { size: 10, label: "size 10 object" }; // labelValue 타입으로 정의
printLabel({ label: myObj });
선택적 프로퍼티
객체 안에 몇 개의 프로퍼티만 채워 함수에 전달, 선언에서 프로퍼티 이름 끝에 ?를 붙여 표시
interface SquareConfig {
color?: string; // 색상명
width?: number; // 둘레 수치
}
function createSquare(config: SquareConfig): {color: string; area: number} {
let newSquare = {color: "white", area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({ color: "black" });
console.log(mySquare);
읽기 프로퍼티
할당 후 수정 불가인 속성, 앞에 readonly를 넣는다.
interface read{
readonly x: string;
readonly y: number;
}
let x1: read = { x: "number", y: 123 };
// x1.x = "apb"; // 오류
// x1.y = 5; // 오류
console.log(x1);
let a: number[] = [1, 2, 3, 4];
let arr: ReadonlyArray<number> = a;
console.log(arr);
초과 프로퍼티 검사
객체 리터럴이 특정 인터페이스나 타입에 할당될 때,
해당 객체에 타입에 정의되지 않은 초과 프로퍼티가 포함되어 있는지 검사하는 과정
interface User {
name: string;
age: number;
}
const user: User = {
name: "Alice",
age: 25,
hobby: "reading", // 에러: 'hobby'는 User 타입에 정의되지 않음
};
User 인터페이스에는 name과 age만 정의되어 있으므로 hobby는 초과 프로퍼티로 간주되어 컴파일 오류를 발생
예외 처리 : 초과 프로퍼티 검사 무시 방법
// 1. 객체 리터럴을 변수에 먼저 할당하는 경우
const obj = { name: "Alice", age: 25, hobby: "reading" };
const user: User = obj; // 오류 없음
// 2. 인덱스 시그니처 사용
interface User {
name: string;
age: number;
[key: string]: any; // 추가 프로퍼티 허용
}
const user: User = {
name: "Alice",
age: 25,
hobby: "reading", // 오류 없음
};
// 3. 타입 단언
const user = {
name: "Alice",
age: 25,
hobby: "reading",
} as User; // 오류 없음
// 4. 객체 확산 연산자 사용
const obj = { name: "Alice", age: 25, hobby: "reading" };
const user: User = { ...obj, hobby: undefined }; // hobby 제거
'TS' 카테고리의 다른 글
| Interface(3) (0) | 2024.11.19 |
|---|---|
| Interface (2) (0) | 2024.11.18 |
| Interface (0) | 2024.11.08 |
| TypeScript의 타입 (이전 글 추가) (0) | 2024.11.07 |
| TypeScript의 타입 (0) | 2024.11.05 |