개발의변화
우아한타입스크립트 3-2 타입조합,제네릭 본문
교차타입
여러가지 타입을 결합하여 하나의 단일 타입으로 만들 수 있다.
&을 사용해서 표기한다. 결과물로 탄생한 단일 타입에는 타입별칭을 붙일 수도 있다.
type ProductItem = {
id: number;
name: string;
type: string;
}
type ProdutItemWithDiscount = ProductITem & { discountAmount : number}
유니온 타입(Union)
교차 타입(A & B)이 타입 A와 타입 B를 모두 만족하는 경우면 유니온타입은 타입A 또는 타입 B중 하나가 될 수 있는 타입을 말하고
A|B
``ts
type CardItem = {
id: number;
name: string;
type: string;
}
type PromotionEventItem = ProductItem | CardItem
``ts
const printPromotionItem = (item: PromotionEventItem) => {
console.log(item.name)
console.log(itme.quantity);
}
인덱스 시그니처(Index Signatures)
특정 타입의 속성 이름은 알 수 없지만 속성값의 타입을 알고 있을 때 사용하는 문법
인터페이스 내부에 [Key: K]: T 꼴로 명시한다
inerface IndexSignatureEx {
[key: string] : number;
isValid: boolean;
length: number;
name: string; //에러 발생
}
인덱스드 엑세스 타입(Indexed Access Types)
인덱스드 엑세스 타입은 다른 타입의 특정 속성이 가지는 타입을 조회하기 위해 사용
type Example = {
a:number;
b:string;
c:boolean;
}
type IndexedAccess =Example["a"];
type IndexedAccess2 = Example["a"|"b"]
type IndexedAcccess3 = Example[keyof Example]
type ExAlias = "b" | "c";
type IndexedAccess4 = Example[ExAlias];
인덱스에 사용되는 타입 또한 그 자체로 타입이기 때문에 유니온타입, keyof, 타입 별칭등의 표현이 있다.
맵드 타입(Mapped Types)
인덱스 시그니처 문법을 반복적인 타입 선언으로 효과적으로 줄일 수 있다.
type Example = {
a: number;
b: string;
c: boolean;
}
type Subset<T> = {
[K in keyof T] ?: T[K];
}
const aExample : Subset<Example> = {a: 3};
const bExample : Subset<Example> = {b: "hello"};
const acExample: Subset<Example> = {a: 4. c: true };
제네릭(Generic)
함수,타입,클래스 등 여러 타입에 대해 하나하나 따로 정의하지 않아도 되기 때문에 재사용성 향상
T(Type), E(Element), K(Key), V(Value) 등 한 글자로 된 이름을 많이 사용
타입을 미리 정해두지 않고 타입 변수를 사용해서 해당 위치를 비워둔 다음에 실제로 그값을 사용할 때 외부에서 타입변수자리에 타입 지정 사용
any와 다른 점: 배열 생성 시점에 원하는 타입으로 특정할 수 있다.
또한 타입을 명시하는 부분을 생략하면 컴파일러가 인수를 보고 타입 추론 ->그러므로 반드시 꺾쇠괄호 안에 타입을 명시해야 하는 것은 아니다.
!중요
제네릭은 일반화된 데이터 타입을 의미하므로 따라서 함수나 클래스 등의 내