➕ zerocho님 typescript all-in-one 강의를 듣고 정리한 내용입니다.
infer : 추론
function zip(x:number, y:string, z:boolean) : {x:number, y:string, z:boolean}{
retunr{x,y,z};
}
type Params = Parameters<typeof zip>; //[x:number, y:string, z:boolean]
type First = Params[0] // number
// key type
type P<T extends (...args:any) => any> = T extends (...args: infer A) => any ? A : never;
// return type
type R<T extends (...args:any) => any> = T extends (...args: any) => infer A ? A : never;
// Constructor type
type ConstructorParameters<T extends abstract new (...args: any) => any> = T extends abstract new (...args: infer P) => any ? P : never;
// Instance type
type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;
class A {
a:string;
b:number;
c:boolean;
Constructor(a:number, b:string, c:boolean){
this.a = a;
this.b = b;
this.c = c;
}
}
const c = new A('123',456,true);
type C = ConstructorParameters<typeof A>; // typeof 클래스가 생성자
type I = InstanceType<typeof A>;
const a : A = new A('123',456,true); // 인스턴스(new)
type 설명에서 intrisic는 typescript로 구현이 어려운 것
const p1 = Promise.resolve(1).then((a) => a+1).then((a) => a-1).then((a) => a.toString())
// Promise<number>, Promise<number>, Promise<number>, Promise<string>
const p2 = Promise.resolve(2) //Promise<number>
const p3 = new Promise((res, rej) => {
setTiemout(res,1000); // Promise<unknown>
})
Promise.all([p1,p2,p3]).then((result) => {
// {'0' :string, '1':number, '2':unknown, length: 3}
console.log(result) // ['1',2,undefined]
})
// T = [p1,p2,p3]
// keyof T = '0' | '1' | '2' | 'length'
Promise 중첩해서도 사용가능
thenable
function a (this : window | typeof obj) {
console.log(this.name)
}
const obj = {name : 'wooyoung'};
const b = a.bind(obj);
b() // 'wooyoung'
// this 추출
type T = ThisParameterType<typeof a> // window | typeof obj
// this를 없앤 함수타입 추출
type NoThis = OmitThisParameterType<typeof a>
bind
const zerocho = {
name: 'zerocho
sayHello(this: { name: string }) (
console. log('hi ${this.name)");
}
const sayHello = zerocho.sayHello; // this가 있음
const sayHi = zerocho.sayHello.bind({ name: 'nero' }); // () => void , bind로 this 없앰
sayHi();
function add(a: number, b: number, c: number, d: number, e: number, f: number) {
return a + b + c+ d + e + f ;
}
const addl = add.bind(null); // null 이 this arg
add1(1, 2, 3, 4, 5, 6);
const add2 - add.bind(null, 1);
add2(2, 3, 4, 5, 6);
const add3 = add.bind(null, 1, 2);
add3(3, 4, 5, 6);
const add4 = add.bind(null, 1, 2, 3);
add4(4, 5, 6);
const add5 = add.bind(null, 1, 2, 3, 4);
add5(5, 6);
flat은 차원(depth)을 낮춤
const a [1,2,3,[1,2],[[1], [2]]].flat() //[1,2,3,1,2,[1],[2]]