2주차 Item 13 ~ 18
type AorB 'a' | 'b' ;
// interface 에서는 불가능
// 별도의 다수의 타입을 하나의 변수명으로 매핑 하는 것은 가능
type Input = { /*...*/ };
type Output = { /*...*/ };
interface VariableMap {
[name: string]: Input | Output
};
// type 일때는
type NamedVariable = (Input | Output) & { name: string };
interface A {
name: string;
}
interface A {
age: number;
}
const a: A = {
name: 'jade',
age: 29,
}
// 정상
interface State = {
userId: string;
pageTitle: string;
recentFiles: string;
}
interface TopNavState = {
userId: State['userId'];
pageTitle: State['pageTitle'];
recentFiles: State['recentFiles'];
}
// 중복 코드 제거 1 '매핑된 타입'
type TopNavState = {
[k in 'userId' | 'pageTitle' | 'recentFiles']: State[k]
};
type TopNavState = Pick<State, 'userId' | 'pageTitle' | 'recentFile'>;
interfact Options {
a: number;
b: number;
c: number;
}
type OptionsUpdate = {[k in keyof Options]?: Options[k]};
// keyof : 타입을 받아서 속성 타입의 유니온을 반환
type OptionsKey = keyof Options;
// type = "a" | "b" | "c"
// 값의 형태에서 해당하는 타입을 정의하고 있다면 typeof 를 사용해도 된다.
// 신중하게 사용!
interface Product {
id: number;
name: string;
stock: number;
}
type shoppingItem = Omit<Product, "stock">;
const apple: Omit<Product, "stock"> = {
id: 1,
name: "red apple",
};
type Vec3D = Record<'x' | 'y' | 'z', number>;
/*
Type vec3D = {
x: number;
y: number;
z: number;
}
*/
type ABC = {[k in 'a' | 'b' | 'c']: k extends 'b' ? string : number};
/*
Type ABC = {
a: number;
b: string;
c: number;
}
*/
function arraySum(arr: readonly number[]) {
...
}
// 배열의 요소를 읽을 수 있지만, 쓸 수는 없다.
// length를 읽을 수 있지만, 바꿀 수는 없다.
// 배열을 변경하는 pop을 비롯한 다른 메서드를 호출할 수 없다.
매핑된 타입을 사용해서 관련된 값과 타입을 동기화한다.
인터페이스에 새로운 속성을 추가할 때, 선택을 강제하도록 매핑된 타입을 고려한다.