typescript - 유틸리티 타입, 이터레이터와 제네레이터

2022. 12. 11. 01:12개발/javascript, typescript

typescript-kr을 보고 공부하고 정리한 글 입니다.

유틸리티 타입

1. Partial

  • 제네릭으로 받은 T 의 모든 타입을 선택적으로 만든다.
  • type Test = { name: string; desc: string; } const obj: Partial<Test> = { name: 'test', desc: 'test desc' }

2.Readonly

  • 읽기 전용으로 만듬
  • type Test = { name: string; desc: string; } const obj: Readonly<Test> = { name: 'test', desc: 'test desc' } // Error readonly property obj.name = 'asdf';

3. Record<K, T>

  • K → object name
  • T → object value (object type)
interface PageInfo {
    title: string;
}

type Page = 'home' | 'about' | 'contact';

const x: Record<Page, PageInfo> = {
    about: { title: 'about' },
    contact: { title: 'contact' },
    home: { title: 'home' },
};

4. Pick <T, K>

  • T object에서 K property 추출
  • interface Todo { title: string; description: string; completed: boolean; } type TodoPreview = Pick<Todo, 'title' | 'completed'>; const todo: TodoPreview = { title: 'Clean room', completed: false, };

5. Omit<T, K>

  • T 에서 K 를 제거한 타입 재구성
  • interface Todo { title: string; description: string; completed: boolean; } type TodoPreview = Omit<Todo, 'description'>; const todo: TodoPreview = { title: 'Clean room', completed: false, };

6. Exclue<T, U>

  • T 에서 U 를 제거한 타입 재구성
  • type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c" type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c" type T2 = Exclude<string | number | (() => void), Function>; // string | number

7. Extract<T, U>

  • T 에서 U 에 해당하는 타입만 재구성
  • type T0 = Extract<"a" | "b" | "c", "a" | "f">; // "a" type T1 = Extract<string | number | (() => void), Function>; // () => void

8.NonNullable

  • T 에서 null, undefined 를 제외한 타입 재구성
  • type T0 = NonNullable<string | number | undefined>; // string | number type T1 = NonNullable<string[] | null | undefined>; // string[]

9.Parameters

  • 함수 paramter의 매개변수 타입들을 추출
  • type PointPrinter = (p: { x: number; y: number; }) => void; // 첫번째 매개변수인 p객체 추출해서 타입으로 재구 const point: Parameters<PointPrinter>[0] = { x: 10, y: 20 }; type T0 = Parameters<() => string>; // [] type T1 = Parameters<(s: string, a: number) => void>; // [string, number] type T2 = Parameters<(<T>(arg: T) => T)>; // [unknown]

10. ConstructorParameters

  • 클래스 생성자 함수의 매개변수 타입들을 추출
  • type T0 = ConstructorParameters<ErrorConstructor>; // [(string | undefined)?] type T1 = ConstructorParameters<FunctionConstructor>; // string[] type T2 = ConstructorParameters<RegExpConstructor>; // [string, (string | undefined)?]

11. ReturnType

  • T 함수의 retun type 추출
  • type T0 = ReturnType<() => string>; // string type T1 = ReturnType<(s: string) => void>; // void

12. InstanceType

  • 생성사 함수 타입(클래스) T 의 인스턴스 타입 추출
  • class C { x = 0; y = 0; } type T0 = InstanceType<typeof C>; // C type T1 = InstanceType<any>; // any type T2 = InstanceType<never>; // any type T3 = InstanceType<string>; // 오류 type T4 = InstanceType<Function>; // 오류

13. Required

  • T 타입의 모든 프로퍼티를 필수로 만듦
  • interface Props { a?: number; b?: string; }; const obj: Props = { a: 5 }; // 성공 const obj2: Required<Props> = { a: 5 }; // 오류: 프로퍼티 'b'가 없습니다

14. ThisParameterType

  • --strictFunctionTypes 가 활성화 되어있을떄만 동작
  • 함수의 this 매개변수의 타입 추출
  • function toHex(this: Number) { return this.toString(16); } function numberToString(n: ThisParameterType<typeof toHex>) { return toHex.apply(n); } numberToString(1) // success numberToString('1') // error: Argument of type 'string' is not assignable to parameter of type 'Number'.

15. OmitThisParameter

  • --strictFunctionTypes 가 활성화 되어있을떄만 동작
  • 함수의 this 매개변수 재거 후 타입 재구성
  • function toHex(this: Number) { return this.toString(16); } // `bind`의 반환 타입은 이미 `OmitThisParameter`을 사용하고 있습니다, 이는 단지 예제를 위한 것입니다. const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5); console.log(fiveToHex());

이터레이터와 제네레이터

  • Object descriptorenumerable 이 true여야 for...of, in 같은이터레이터 사용가능
    • descriptor: object.getOwonPropertyDescriptor(ConsoleLogger.prototype, 'log')

for…of , for…in

let list = [4, 5, 6];

// for...in 은 이터레이터의 key 반환. 모든 객체에서 작동
for (let i in list){
 console.log(i); // "0", "1", "2"
}

// for...of는 이터레이터의 value 반환
for (let i of list){
 console.log(i); // "4", "5", "6"
}

'개발 > javascript, typescript' 카테고리의 다른 글

Immer가 무엇인가요?  (0) 2022.08.24
[인사이드 자바스크립트] Javascript 기초  (0) 2021.08.29
Javascript Event와 Polyfill, babel  (0) 2021.08.29
[Javascript] - Predicate  (0) 2020.09.26
[JavaScript] - for...of  (0) 2020.08.21