TypeScript는 일반적인 타입 변환을 쉽게 하기 위해서 몇 가지 유틸리티 타입을 제공합니다. 이러한 유틸리티는 전역으로 사용 가능합니다.
Partial<Type>
Type 집합의 모든 프로퍼티를 선택적으로 타입을 생성합니다. 이 유틸리티는 주어진 타입의 모든 하위 타입 집합을 나타내는 타입을 반환합니다.
예제
tsTryinterfaceTodo {title : string;description : string;}functionupdateTodo (todo :Todo ,fieldsToUpdate :Partial <Todo >) {return { ...todo , ...fieldsToUpdate };}consttodo1 = {title : "organize desk",description : "clear clutter",};consttodo2 =updateTodo (todo1 , {description : "throw out trash",});
Required<Type>
Type 집합의 모든 프로퍼티를 필수로 설정한 타입을 생성합니다. Partial의 반대입니다.
예제
tsTryinterfaceProps {a ?: number;b ?: string;}constobj :Props = {a : 5 };constProperty 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.2741Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.: obj2 Required <Props > = {a : 5 };
Readonly<Type>
Type 집합의 모든 프로퍼티읽기 전용(readonly)으로 설정한 타입을 생성합니다, 즉 생성된 타입의 프로퍼티는 재할당될 수 없습니다.
예제
tsTryinterfaceTodo {title : string;}consttodo :Readonly <Todo > = {title : "Delete inactive users",};Cannot assign to 'title' because it is a read-only property.2540Cannot assign to 'title' because it is a read-only property.todo .= "Hello"; title
이 유틸리티는 런타임에 실패할 할당 표현식을 표현할 때 유용합니다(예. frozen 객체 의 프로퍼티에 재할당하려고 하는 경우).
Object.freeze
tsfunction freeze<Type>(obj: Type): Readonly<Type>;
Record<Keys,Type>
타입 Type의 프로퍼티 키의 집합으로 타입을 생성합니다. 이 유틸리티는 타입의 프로퍼티를 다른 타입에 매핑 시키는데 사용될 수 있습니다.
예제
tsTryinterfacePageInfo {title : string;}typePage = "home" | "about" | "contact";constnav :Record <Page ,PageInfo > = {about : {title : "about" },contact : {title : "contact" },home : {title : "home" },};nav .about ;
Pick<Type, Keys>
Type에서 프로퍼티 Keys의 집합을 선택해 타입을 생성합니다.
예제
tsTryinterfaceTodo {title : string;description : string;completed : boolean;}typeTodoPreview =Pick <Todo , "title" | "completed">;consttodo :TodoPreview = {title : "Clean room",completed : false,};todo ;
Omit<Type, Keys>
Type에서 모든 프로퍼티를 선택하고 키를 제거한 타입을 생성합니다.
예제
tsTryinterfaceTodo {title : string;description : string;completed : boolean;}typeTodoPreview =Omit <Todo , "description">;consttodo :TodoPreview = {title : "Clean room",completed : false,};todo ;
Exclude<Type, ExcludedUnion>
ExcludedUnion에 할당할 수 있는 모든 유니온 멤버를 Type에서 제외하여 타입을 생성합니다.
예제
tsTrytypeT0 =Exclude <"a" | "b" | "c", "a">;typeT1 =Exclude <"a" | "b" | "c", "a" | "b">;typeT2 =Exclude <string | number | (() => void),Function >;
Extract<Type, Union>
Union에 할당할 수 있는 모든 유니온 멤버를 Type에서 가져와서 타입을 생성합니다.
예제
tsTrytypeT0 =Extract <"a" | "b" | "c", "a" | "f">;typeT1 =Extract <string | number | (() => void),Function >;
NonNullable<Type>
Type에서 null과 정의되지 않은 것(undefined)을 제외하고 타입을 생성합니다.
예제
tsTrytypeT0 =NonNullable <string | number | undefined>;typeT1 =NonNullable <string[] | null | undefined>;
Parameters<Type>
함수 타입 Type의 매개변수에 사용된 타입에서 튜플 타입을 생성합니다.
예제
tsTrydeclare functionf1 (arg : {a : number;b : string }): void;typeT0 =Parameters <() => string>;typeT1 =Parameters <(s : string) => void>;typeT2 =Parameters <<T >(arg :T ) =>T >;typeT3 =Parameters <typeoff1 >;typeT4 =Parameters <any>;typeT5 =Parameters <never>;typeType 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.T6 =Parameters <string >;typeType 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.T7 =Parameters <>; Function
ConstructorParameters<Type>
생성자 함수 타입의 타입에서 튜플 또는 배열 타입을 생성합니다. 모든 매개변수 타입을 가지는 튜플 타입(또는 Type이 함수가 아닌 경우 타입 never)을 생성합니다.
예제
tsTrytypeT0 =ConstructorParameters <ErrorConstructor >;typeT1 =ConstructorParameters <FunctionConstructor >;typeT2 =ConstructorParameters <RegExpConstructor >;typeT3 =ConstructorParameters <any>;typeType 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.T4 =ConstructorParameters <>; Function
ReturnType<Type>
함수 Type의 반환 타입으로 구성된 타입을 생성합니다.
예제
tsTrydeclare functionf1 (): {a : number;b : string };typeT0 =ReturnType <() => string>;typeT1 =ReturnType <(s : string) => void>;typeT2 =ReturnType <<T >() =>T >;typeT3 =ReturnType <<T extendsU ,U extends number[]>() =>T >;typeT4 =ReturnType <typeoff1 >;typeT5 =ReturnType <any>;typeT6 =ReturnType <never>;typeType 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.T7 =ReturnType <string >;typeType 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.T8 =ReturnType <>; Function
InstanceType<Type>
Type의 생성자 함수의 인스턴스 타입으로 구성된 타입을 생성합니다.
예제
tsTryclassC {x = 0;y = 0;}typeT0 =InstanceType <typeofC >;typeT1 =InstanceType <any>;typeT2 =InstanceType <never>;typeType 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.2344Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.T3 =InstanceType <string >;typeType 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.T4 =InstanceType <>; Function
ThisParameterType<Type>
함수 타입의 this 매개변수의 타입, 또는 함수 타입에 this매개변수가 없을 경우 unknown 을 추출합니다.
예제
tsTryfunctiontoHex (this :Number ) {return this.toString (16);}functionnumberToString (n :ThisParameterType <typeoftoHex >) {returntoHex .apply (n );}
OmitThisParameter<Type>
Type에서 this 매개변수를 제거합니다. Type에 명시적으로 선언된 this매개변수가 없는 경우에, 단순히 Type입니다. 반면에, this매개변수가 없는 새로운 함수 타입은 Type에서 생성됩니다. 제네릭은 사라지고 마지막 오버로드 시그니처만 새로운 함수 타입으로 전파됩니다.
예제
tsTryfunctiontoHex (this :Number ) {return this.toString (16);}constfiveToHex :OmitThisParameter <typeoftoHex > =toHex .bind (5);console .log (fiveToHex ());
ThisType<Type>
이 유틸리티는 변형된 타입을 반환하지 않습니다. 대신에, 문맥적 this 타입에 표시하는 역할을 합니다. 이 유틸리티를 사용하기 위해서는 --noImplicitThis 플래그를 사용해야 하는 것을 기억하세요.
예제
tsTrytypeObjectDescriptor <D ,M > = {data ?:D ;methods ?:M &ThisType <D &M >; // Type of 'this' in methods is D & M};functionmakeObject <D ,M >(desc :ObjectDescriptor <D ,M >):D &M {letdata : object =desc .data || {};letmethods : object =desc .methods || {};return { ...data , ...methods } asD &M ;}letobj =makeObject ({data : {x : 0,y : 0 },methods : {moveBy (dx : number,dy : number) {this.x +=dx ; // Strongly typed thisthis.y +=dy ; // Strongly typed this},},});obj .x = 10;obj .y = 20;obj .moveBy (5, 5);
위 예제에서, makeObject의 인수인 methods 객체는 ThisType<D & M> 을 포함한 문맥적 타입을 가지고 따라서 methods 객체의 메서드 안에 this 타입은 { x: number, y: number } & { moveBy(dx: number, dy: number): number }입니다. methods 프로퍼티의 타입은 추론 대상인 동시에 메서드의 this 타입의 출처인 것에 주목하세요.
ThisType<T> 마커 인터페이스는 단지 lib.d.ts에 선언된 빈 인터페이스입니다. 객체 리터럴의 문맥적 타입으로 인식되는 것을 넘어, 그 인터페이스는 빈 인터페이스처럼 동작합니다.
내장 문자열 조작 타입
Uppercase<StringType>
Lowercase<StringType>
Capitalize<StringType>
Uncapitalize<StringType>
템플릿 문자열 리터럴에서의 문자열 조작을 돕기 위해, TypeScript는 타입 시스템 내에서 문자열 조작에 사용할 수 있는 타입 집합이 포함되어 있습니다. 이 링크에서 예제를 확인하세요.