타입스크립트의 타입은 Structural Subtyping 이라는 규칙을 따른다
:상속 관계가 명시되어 있지 않더라도 객체의 프로퍼티를 기반으로 사용처에서 사용함에 문제가 없다면 타입 호환을 허용하는 방식
interface A {
a: string;
}
interface B {
b: number;
}
function printA(arg: A) {
console.log(arg.a);
}
const x = { a: 'codeit' };
const y = { b: 42 };
const z = { a: 'codeit', b: 42 };
const w = { a: 'codeit', b: 42, c: true };
printA(x);
printA(y); // 잘못된 타입
printA(z);
printA(w);
함수 printA 는 A 타입의 인자를 받아 a 프로퍼티 값을 출력한다.
이때 {a }가 포함되어있는 x, z, w 를 타입 A 라고 판단하기때문에 오류가 나지않는다.
Union
A|B|C|D|...
function printAUnionB(arg: A | B) {
// 여기서는 타입 A | B
if ('a' in arg) {
// 여기 안에서는 타입 A
console.log(arg.a);
}
if ('b' in arg) {
// 여기 안에서는 타입 B
console.log(arg.b); // VS Code에서 arg에 마우스를 호버해 보세요.
}
}
if in 구문을 사용해서, 해당 프로퍼티가 존재할때 조건문 실행 : Type Narrowing 이라고 한다.
Intersection
A&B&C&D&...
interface A {
a: string;
}
interface B {
b: number;
}
function printAIntersectionB(arg: A & B) {
console.log(arg.a);
console.log(arg.b);
}
const x = { a: 'codeit' };
const y = { b: 42 };
const z = { a: 'codeit', b: 42 };
const w = { a: 'codeit', b: 42, c: true };
printAIntersectionB(x); // 타입 오류
printAIntersectionB(y); // 타입 오류
printAIntersectionB(z);
printAIntersectionB(w);
A&B 타입은 {a, b} 두 프로퍼티를 모두 가지고있는 타입
'개발 공부 일지 > TypeScript' 카테고리의 다른 글
타입스크립트 - 제네릭 (0) | 2024.09.13 |
---|---|
타입스크립트 - keyof, typeof (0) | 2024.09.11 |
타입스크립트 - 리터럴 타입 / 타입 별칭 (0) | 2024.09.10 |
타입스크립트 - interface (0) | 2024.09.10 |
타입스크립트 - enum (0) | 2024.09.10 |