Partial<Type>
: Type 집합의 모든 프로퍼티를 선택적으로 가져와 타입을 정의
- 예시
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>'.
ReadOnly<Type>
: Type 집합의 모든 프로퍼티를 읽기 전용으로 정의
: 런타임에 실패할 할당 표현식을 표현할 때 유용
- 예시
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.
Record<Keys, Type>
: Type 프로퍼티 키의 집합으로 타입을 생성
: 타입의 프로퍼티를 다른 타입에 매핑 시킬때 유용
- 예시
interface PageInfo {
title: string;
}
type Page = "home" | "about" | "contact";
const nav: Record<Page, PageInfo> = {
about: { title: "about" },
contact: { title: "contact" },
home: { title: "home" },
};
nav.about;
const nav: Record<Page, PageInfo>
Pick<Type, Keys>
: Type 에서 프로퍼티 Keys의 집합을 선택해 타입을 생성
- 예시
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
const todo: TodoPreview
Omit<Type, Keys>
: Type에서 모든 프로퍼티를 선택하고 Key를 제거한 타입을 생성
- 예시
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
const todo: TodoPreview
Exclude<Type, ExcludeUnion>
: ExcludedUnion에 할당할 수 있는 모든 유니온 멤버를 Type에서 제외하여 타입 생성
- 예시
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>
: 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>
: Type에서 null과 undefined를 제외하고 타입을 생성
- 예시
type T0 = NonNullable<string | number | undefined>;
type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
type T1 = string[]
Paramerters<Type>
: 함수 타입 Type의 매개변수에 사용된 타입에서 튜플 타입을 생성
: 함수 타입의 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 = never
type T6 = Parameters<string>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T6 = never
type 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 T7 = never
ConstructorParameters<Type>
: 생성자 함수 타입에서 튜플 또는 배열 타입을 생성
: 생성자에 대한 타입 지정
- 예시
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 T4 = never
ReturnType<Type>
: 함수 Type의 반환 타입 정의
- 예시
declare function f1(): { a: number; b: string };
type T0 = ReturnType<() => string>;
type T0 = string
type T1 = ReturnType<(s: string) => void>;
type T1 = void
type T2 = ReturnType<<T>() => T>;
type T2 = unknown
type 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 = any
type T6 = ReturnType<never>;
type T6 = never
type T7 = ReturnType<string>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T7 = any
type 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 T8 = any
InstanceType<Type>
: Type의 생성자 함수의 인스턴스 타입으로 구성된 타입 생성
- 예시
class C {
x = 0;
y = 0;
}
type T0 = InstanceType<typeof C>;
type T0 = C
type T1 = InstanceType<any>;
type T1 = any
type T2 = InstanceType<never>;
type T2 = never
type T3 = InstanceType<string>;
Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
type T3 = any
type T4 = InstanceType<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 T4 = any
ThisParameterType<Type>
: 함수 타입의 this 매개변수의 타입을 추출
: 매개변수가 없을 경우 unknown을 추출
- 예시
function toHex(this: Number) {
return this.toString(16);
}
function numberToString(n: ThisParameterType<typeof toHex>) {
return toHex.apply(n);
}
OmitThisParameter<Type>
: Type에서 this 매개변수를 제거한 타입을 정의
- 예시
function toHex(this: Number) {
return this.toString(16);
}
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
console.log(fiveToHex());
ThisType<Type>
: 변형된 타입을 반환하지 않고 문맥적 this 타입에 표시
: 해당 타입을 사용하기 위해서는 --noImplictThis 플래그로 컴파일 해야함
- 예시
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);
내장 문자열 조작 타입
- Uppercase<StringType>
- Lowercase<StringType>
- Capitalize<StringType>
- Uncapitalize<StringType>
Reference
Documentation - Utility Types
Types which are globally included in TypeScript
www.typescriptlang.org
'Programming > TypeScript' 카테고리의 다른 글
타입스크립트로 배우는 SOLID 원칙 (0) | 2023.09.12 |
---|---|
타입스크립트 설치 및 초기세팅 (0) | 2023.07.07 |
ts-pattern을 활용한 선언적 분기 작성 (0) | 2023.05.29 |
tsc (TypeScript Compiler) (0) | 2023.04.30 |
타입스크립트 (TypeScript) 란? (0) | 2023.04.30 |