본문 바로가기

IT/typescript34

TS - unknown vs any 개념 unknown, any 타입을 지정하기 애매할 때 사용 unknown 타입이 뭔지 모르겠으니 개발자가 타입을 정확히 지정주어야 한다. typeof, instanceof 등 타입을 확인하여 적절한 타입 주입시켜 사용한다. Example code reference: https://docs.nestjs.com/exception-filters#catch-everything @Catch() export class AllExceptionsFilter implements ExceptionFilter { constructor(private readonly httpAdapterHost: HttpAdapterHost) {} catch(exception: unknown, host: ArgumentsHost): void.. 2023. 6. 27.
TS - never 개념 Bottom type을 나타내기 위해 사용하는 것 어떠한 값도 할당할 수 없다. Exhaustive Check (Bottom type) function foo(x: string | number): boolan { if (typeof x === 'string') { return true } else if (typeof x === 'number') { return false } return fail() } function fail(): never { throw new Error() } 어떠한 값도 할당할 수 없다. let a: never = null // Type 'null' is not assignable to type 'never'.(2322) let b: never = undefined // Ty.. 2023. 6. 27.
TS - Extract<T, U> 개념 한마디로, T에서 U타입 중 할당 가능한 것만 리턴 정리하지면, pick은 prop을, extract는 type을... type Extract = T extends U ? T : never Examples type Company = { id: string name: string } type Product = { price: number rating: number } type fakeProduct = Extract // type fakeProduct = { // id: string; // name: string; // } 참고 https://velog.io/@ggong/Typescript의-유틸리티-타입-1-Record-Extract-Pick 2023. 6. 27.
TS - Exclude<T, U> 개념 한마디로, T에서 U를 제외시킨 Type U를 제외시킬 수 없다면 T 그대로 리턴 T에 union type 받을 수 있음 type Exclude = T extends U ? never : T Examples Only number type numberOnly = Exclude const a: numberOnly = 5 // const a: number how it works Exclude => Exclude | Exclude => string | never => => string Remove props in interface interface Student { name: string age: number address: string gpa: number } type refiendStudent = Ex.. 2023. 6. 27.