아이템6
편집기를 사용하여 타입시스템 탐색하기// Request를 생성할 때 사용할 수 있는 옵션
interface RequestInit {
body?: BodyInit | null;
cache?: RequestCache;
credentials?: RequestCredentials;
headers?: HeadersInit;
// ...
}
아이템7
타입이 값들의 집합이라고 생각하기// 속성(프로퍼티)들의 집합이 아니라 타입이 될 수 있는 값의 집합임을 이해하기
interface Person {
name: string;
}
interface Lifespan {
birth: Date;
death?: Date;
}
type PersonSpan = Person & Lifespan;
type K = keyof (Person | Lifespan); // Type is never
// extends가 제네릭 타입에서 한정자로 쓰인다
function getKey<K extends string>(val: any, key: K) {
// ...
}
getKey({}, 'x'); // OK, 'x' extends string
getKey({}, Math.random() < 0.5 ? 'a' : 'b'); // OK, 'a'|'b' extends string
getKey({}, document.title); // OK, string extends string
getKey({}, 12);
// ~~ Type '12' is not assignable to parameter of type 'string'
// 타입이 되지 못하는 값의 집합 예시
type T = Exclude<string | Date, string | number>; // Type is Date
type NonZeroNums = Exclude<number, 0>; // Type is still just number
아이템8
타입공간의 심벌인지 값공간의 심벌인지 구분 잘 하기type User = {
name: string;
age: number;
};
const user: User = {
name: 'jinwook',
age: 20,
};
type User = {
readonly name: 'jinwook';
readonly age: 20;
};
const user: User = {
name: 'jinwook',
age: 20,
} as const;
this
타입 (Polymorphic this types)다형성 this 타입은 포함하는 클래스나 인터페이스의 하위 타입을 나타냅니다. F-bounded polymorphism이라고 부릅니다. 예를 들어, 계층적으로 유연한 인터페이스를 표현하기 더 쉽게 만듭니다. 각 연산 후에 this를 반환하는 간단한 계산기를 보겠습니다
class BasicCalculator {
public constructor(protected value: number = 0) {}
public currentValue(): number {
return this.value;
}
public add(operand: number): this {
this.value += operand;
return this;
}
public multiply(operand: number): this {
this.value *= operand;
return this;
}
// ... 다른 연산들은 여기에 작성 ...
}
let v = new BasicCalculator(2).multiply(5).add(1).currentValue();
클래스가 this 타입을 사용하기 때문에, 이를 extend 할 수 있고 새로운 클래스가 아무 변경 없이 이전 메서드를 사용할 수 있습니다.
class ScientificCalculator extends BasicCalculator {
public constructor(value = 0) {
super(value);
}
public sin() {
this.value = Math.sin(this.value);
return this;
}
// ... 다른 연산들은 여기에 작성 ...
}
let v = new ScientificCalculator(2).multiply(5).sin().add(1).currentValue();
this 타입 없이, ScientificCalculator는 BasicCalculator를 extend 할 수 없을 것이고 유연한 인터페이스를 유지하지 못할 것입니다. multiply는 sin 메서드를 가지지 않는 BasicCalculator를 반환합니다. 하지만, this 타입으로, multiply는 this를 반환하고, 여기서는 ScientificCalculator을 말합니다.
아이템9
타입단언 보다는 타입선언을아이템10
객체 래퍼 타입 입히기아이템11
잉여 속성 체크의 한계interface A {
a?: string;
b?: string;
}
const a = {};
const b = { c: 'a' };
const c: A = b; // 이런걸 임시변수를 사용한 할당이라고 함..
// ~~ '{ c: string; }' 유형에 'A' 유형과 공통적인 속성이 없습니다.