lottie
Seungjun's blog
blog
유틸리티 유형

  typeScript는 일반적인 유형 변환을 용이하게 하기 위해 여러 유틸리티 유형을 제공합니다. 이러한 유틸리티는 전 세계적으로 사용할 수 있습니다.

Partial<Type>

 모든 속성이 Typeoptional로 설정된 형식을 생성합니다. 이 유틸리티는 주어진 유형의 모든 하위 집합을 나타내는 유형을 반환합니다.


예시

interface Todo {
  title: string;
  description: string;
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}
const todo1 = {
  title: "organize desk",
  description: "clear clutter",
};
const todo2 = updateTodo(todo1, {
  description: "throw out trash",
});


Required<Type>

 Type필수로 설정된 모든 속성으로 구성된 유형을 구성 합니다. 


예시

interface Props {
  a?: number;
  b?: string;
}
const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 };
//
Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.

Readonly<Type>

 모든 속성이 로 Type설정된 readonly형식을 생성합니다. 이는 생성된 형식의 속성을 다시 할당할 수 없음을 의미합니다.


예시

interface Todo {
  title: string;
}
const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};
todo.title = "Hello";
Cannot assign to 'title' because it is a read-only property.Cannot assign to 'title' because it is a read-only property.노력하다

이 유틸리티는 런타임에 실패할 할당 표현식을 나타내는 데 유용합니다.


Object.freeze

function freeze<Type>(obj: Type): Readonly<Type>;


Record<Keys, Type>

 Keys속성 키가 이고 속성 값이 인 개체 유형을 구성합니다 Type. 이 유틸리티는 유형의 속성을 다른 유형에 매핑하는 데 사용할 수 있습니다.


예시

interface CatInfo {
  age: number;
  breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
  mordred: { age: 16, breed: "British Shorthair" },
};
cats.boris;
 const cats: Record<CatName, CatInfo>노력하다


Pick<Type, Keys>

 Keys에서 속성 집합 (문자열 리터럴 또는 문자열 리터럴의 합집합)을 선택하여 형식을 구성합니다.


예시

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};


Omit<Type, Keys>

 모든 속성을 Type선택한 다음 제거 하여 형식을 구성합니다 Keys(문자열 리터럴 또는 문자열 리터럴의 합집합).


예시

interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
  createdAt: 1615544252770,
};
todo;
 const todo: TodoPreview
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
const todoInfo: TodoInfo = {
  title: "Pick up kids",
  description: "Kindergarten closes at 5pm",
};
todoInfo;
   const todoInfo: TodoInfo노력하다


Exclude<UnionType, ExcludedMembers>

 UnionType에 할당할 수 있는 모든 공용체 구성원 에서 제외하여 형식을 생성합니다 ExcludedMembers.


예시

type T0 = Exclude<"a" | "b" | "c", "a">;
     type T0 = "b" | "c"type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
     type T1 = "c"type T2 = Exclude<string | number | (() => void), Function>;
     type T2 = string | number노력하다


Extract<Type, Union>

 Type에 할당할 수 있는 모든 공용체 구성원 에서 추출하여 형식을 생성합니다 .


예시

type T0 = Extract<"a" | "b" | "c", "a" | "f">;
     type T0 = "a"type T1 = Extract<string | number | (() => void), Function>;
     type T1 = () => void노력하다


NonNullable<Type>

 null및 undefinedfrom 을 제외하여 형식을 구성합니다.


예시

type T0 = NonNullable<string | number | undefined>;
     type T0 = string | numbertype T1 = NonNullable<string[] | null | undefined>;
     type T1 = string[]노력하다


Parameters<Type>

 함수 유형의 매개변수에 사용된 유형에서 튜플 유형을 구성합니다 .


예시

declare function f1(arg: { a: number; b: string }): void;
type T0 = Parameters<() => string>;
     type T0 = []type T1 = Parameters<(s: string) => void>;
     type T1 = [s: string]type T2 = Parameters<<T>(arg: T) => T>;
     type T2 = [arg: unknown]type T3 = Parameters<typeof f1>;
     type T3 = [arg: {
    a: number;
    b: string;
}]type T4 = Parameters<any>;
     type T4 = unknown[]type T5 = Parameters<never>;
     type T5 = nevertype T6 = Parameters<string>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.Type 'string' does not satisfy the constraint '(...args: any) => any'.     type T6 = nevertype T7 = Parameters<Function>;
Type 'Function' does not satisfy the constraint '(...args: any) => any'.
  Type 'Function' provides no match for the signature '(...args: any): any'.Type 'Function' does not satisfy the constraint '(...args: any) => any'.
  Type 'Function' provides no match for the signature '(...args: any): any'.     
  type T7 = never노력하다

ConstructorParameters<Type>

 생성자 함수 유형의 유형에서 튜플 또는 배열 유형을 생성합니다. 모든 매개변수 유형(또는 함수가 아닌 never경우 유형)이 있는 튜플 유형을 생성합니다.


예시

type T0 = ConstructorParameters<ErrorConstructor>;
     type T0 = [message?: string]type T1 = ConstructorParameters<FunctionConstructor>;
     type T1 = string[]type T2 = ConstructorParameters<RegExpConstructor>;
     type T2 = [pattern: string | RegExp, flags?: string]type T3 = ConstructorParameters<any>;
     type T3 = unknown[]
type T4 = ConstructorParameters<Function>;
Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
  Type 'Function' provides no match for the signature 'new (...args: any): any'.Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
  Type 'Function' provides no match for the signature 'new (...args: any): any'.     type T4 = never노력하다


ReturnType<Type>

function 의 반환 유형으로 구성된 유형을 구성합니다 .


예시

declare function f1(): { a: number; b: string };
type T0 = ReturnType<() => string>;
     type T0 = stringtype T1 = ReturnType<(s: string) => void>;
     type T1 = voidtype T2 = ReturnType<<T>() => T>;
     type T2 = unknowntype T3 = ReturnType<<T extends U, U extends number[]>() => T>;
     type T3 = number[]type T4 = ReturnType<typeof f1>;
     type T4 = {
    a: number;
    b: string;
}type T5 = ReturnType<any>;
     type T5 = anytype T6 = ReturnType<never>;
     type T6 = nevertype T7 = ReturnType<string>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.Type 'string' does not satisfy the constraint '(...args: any) => any'.     type T7 = anytype T8 = ReturnType<Function>;
Type 'Function' does not satisfy the constraint '(...args: any) => any'.
  Type 'Function' provides no match for the signature '(...args: any): any'.Type 'Function' does not satisfy the constraint '(...args: any) => any'.
  Type 'Function' provides no match for the signature '(...args: any): any'.     
  type T8 = any노력하다




ThisType<Type>

 이 유틸리티는 변환된 유형을 반환하지 않습니다. 대신 컨텍스트 유형에 대한 마커 역할을 합니다. 이 유틸리티를 사용 하려면플래그를 활성화해야 합니다.


예시

type ObjectDescriptor<D, M> = {
  data?: D;
  methods?: M & ThisType<D & M>; // Type of 'this' in methods is D & M
};
function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
  let data: object = desc.data || {};
  let methods: object = desc.methods || {};
  return { ...data, ...methods } as D & M;
}
let obj = makeObject({
  data: { x: 0, y: 0 },
  methods: {
    moveBy(dx: number, dy: number) {
      this.x += dx; // Strongly typed this
      this.y += dy; // Strongly typed this
    },
  },
});

obj.x = 10;
obj.y = 20;
obj.moveBy(5, 5);

 위의 예 methods에서 에 대한 인수의 객체는 makeObject를 포함하는 컨텍스트 유형을 가지므로 객체 내의 메소드에서 ThisType<D & M> 의 유형 은 입니다 . 속성의 유형이 메서드의 유형에 대한 유추 대상이자 소스 인 방법에 주목하십시오.


 ThisType<T>마커 인터페이스는 단순히 에 선언된 빈 인터페이스 입니다 lib.d.ts. 객체 리터럴의 컨텍스트 유형에서 인식되는 것 외에도 인터페이스는 빈 인터페이스처럼 작동합니다.


고유 문자열 조작 유형

Uppercase<StringType>

Lowercase<StringType>

Capitalize<StringType>

Uncapitalize<StringType>

  템플릿 문자열 리터럴에 대한 문자열 조작을 돕기 위해 TypeScript에는 유형 시스템 내에서 문자열 조작에 사용할 수 있는 유형 집합이 포함되어 있습니다.