taesik

Utility Type 본문

Concepts/TypeScript

Utility Type

taesikk 2021. 12. 28. 12:07

TypeScript provides several utility types to facilitate common type conversions. These utilities are available globally.

 

 

Partial<T>

It constructs a type that makes all properties of T optional. This utility returns a type representing the set of all subtypes of a given type.

 

interface Todo {
    title: string;
    description: string;
}

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
    return { ...todo, ...fieldsToUpdate };
}

const todoFirst = {
    title: 'organize desk',
    description: 'clear clutter',
};

const todoSecond = updateTodo(todo1, {
    description: 'throw out trash',
});

Readonly<T>

It constructs a type with all properties of T set to readonly, i.e. properties of the created type cannot be reassigned.

 

interface Todo {
    title: string;
}

const todo: Readonly<Todo> = {
    title: 'study',
};

todo.title = 'Hello'; 
//// error: cannot reassign to read-only property

This utility is useful when indicating an assignment expression that will fail at runtime (eg when trying to reallocate a property of a frozen object).

object. freeze

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

Record<K,T>

interface DocInfo {
    title: string;
}

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

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

Pick<T,K>

It select a set of properties K from T to form a type.

 

interface record {
    title: string;
    description: string;
    completed: boolean;
}

type recordPreview = Pick<record, 'title' | 'completed'>;

const record: recordPreview = {
    title: 'title',
    completed: false,
};

Omit<T,K>

It select all properties from T and then construct the type with K removed.

interface Record {
    title: string;
    description: string;
    completed: boolean;
}

type RecordPreview = Omit<Record, 'description'>;

const todo: RecordPreview = {
    title: 'title',
    completed: false,
};

Exclude<T,U>

It constructs a type from T except for all properties assignable to 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

Extract<T,U>

It constructs a type by extracting all assignable properties from T to U.

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

NonNullable<T>

It constructs types other than null and undefined in T.

type T0 = NonNullable<string | number | undefined>;  // string | number
type T1 = NonNullable<string[] | null | undefined>;  // string[]

Parameters<T>

It constructs a tuple type of parameter types of function type T.

declare function f1(arg: { a: number, b: string }): void
type T0 = Parameters<() => string>;  // []
type T1 = Parameters<(s: string) => void>;  // [string]
type T2 = Parameters<(<T>(arg: T) => T)>;  // [unknown]
type T4 = Parameters<typeof f1>;  // [{ a: number, b: string }]
type T5 = Parameters<any>;  // unknown[]
type T6 = Parameters<never>;  // never
type T7 = Parameters<string>;  // Error
type T8 = Parameters<Function>;  // Error

ConstructorParameters<T>

The ConstructorParameters<T> type allows you to extract the types of all parameters of a constructor function type. It creates a tuple type (never if T is not a function) with all parameter types.

type T0 = ConstructorParameters<ErrorConstructor>;  // [(string | undefined)?]
type T1 = ConstructorParameters<FunctionConstructor>;  // string[]
type T2 = ConstructorParameters<RegExpConstructor>;  // [string, (string | undefined)?]

ReturnType<T>

It create a type that consists of the return type of the function T.

declare function f1(): { a: number, b: string }
type T0 = ReturnType<() => string>;  // string
type T1 = ReturnType<(s: string) => void>;  // void
type T2 = ReturnType<(<T>() => T)>;  // {}
type T3 = ReturnType<(<T extends U, U extends number[]>() => T)>;  // number[]
type T4 = ReturnType<typeof f1>;  // { a: number, b: string }
type T5 = ReturnType<any>;  // any
type T6 = ReturnType<never>;  // any
type T7 = ReturnType<string>;  // error
type T8 = ReturnType<Function>;  // error

InstanceType<T>

It constructs a type consisting of an instance type of the constructor function type 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>;  // error
type T4 = InstanceType<Function>;  // error

Required<T>

It makes a type with all properties of T set to required.

interface Props {
    a?: number;
    b?: string;
};

const obj: Props = { a: 5 }; // success

const obj2: Required<Props> = { a: 5 }; // error: no property 'b'

ThisParameterType

If the type of the this parameter of the function type or the function type does not have a this parameter, unknown is extracted.

Note: This type only works correctly when --strictFunctionTypes is enabled.

function toHex(this: Number) {
    return this.toString(16);
}

function numberToString(n: ThisParameterType<typeof toHex>) {
    return toHex.apply(n);
}

 

'Concepts > TypeScript' 카테고리의 다른 글

Count instance in object  (0) 2022.04.06
curring  (0) 2022.01.23
increase 1 per 1second using closure function  (0) 2022.01.23
closure 1 - return result of function /return function  (0) 2022.01.23