17

Partial<Type>

Construct the type Type and set all its attributes to optional. Its return type represents all subtypes of the input type.

example

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',
});

Readonly<Type>

Construct the type Type and set all its properties to readonly , which means that the properties of the constructed type cannot be assigned again.

example

interface Todo {
    title: string;
}

const todo: Readonly<Todo> = {
    title: 'Delete inactive users',
};

todo.title = 'Hello'; // Error: cannot reassign a readonly property

This tool can be used to express assignment expressions that fail at runtime (for example, when trying to re-assign the properties of the frozen object

Object.freeze

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

Record<Keys, Type>

Construct a type, the type of the attribute name is K , and the type of the attribute value is T . This tool can be used to map attributes of one type to another.

example

interface PageInfo {
    title: string;
}

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

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

Pick<Type, Keys>

Select some attributes Keys from the type Type to construct the type.

example

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>

Get all the attributes from the type Type , and then construct a type after Keys

example

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

type TodoPreview = Omit<Todo, 'description'>;

const todo: TodoPreview = {
    title: 'Clean room',
    completed: false,
};

Exclude<Type, ExcludedUnion>

Remove all attributes that can be assigned to ExcludedUnion from the type Type , and then construct a type.

example

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<Type, Union>

Extract all types that can be assigned to Union from the type Type , and then construct a type.

example

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

NonNullable<Type>

null and undefined from the type Type , and then construct a type.

example

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

Parameters<Type>

A tuple type is constructed from the parameter types of the function type Type

example

declare function f1(arg: { a: number; b: string }): void;

type T0 = Parameters<() => string>;
//    []
type T1 = Parameters<(s: string) => void>;
//    [s: string]
type T2 = Parameters<<T>(arg: T) => T>;
//    [arg: unknown]
type T3 = Parameters<typeof f1>;
//    [arg: { a: number; b: string; }]
type T4 = Parameters<any>;
//    unknown[]
type T5 = Parameters<never>;
//    never
type T6 = Parameters<string>;
//   never
//   Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T7 = Parameters<Function>;
//   never
//   Type 'Function' does not satisfy the constraint '(...args: any) => any'.

ConstructorParameters<Type>

Construct a tuple type or array type by the constructor type.
A tuple type is constructed from the parameter types of the constructor type Type (If Type is not a constructor type, return never ).

example

type T0 = ConstructorParameters<ErrorConstructor>;
//    [message?: string | undefined]
type T1 = ConstructorParameters<FunctionConstructor>;
//    string[]
type T2 = ConstructorParameters<RegExpConstructor>;
//    [pattern: string | RegExp, flags?: string | undefined]
type T3 = ConstructorParameters<any>;
//   unknown[]

type T4 = ConstructorParameters<Function>;
//    never
// Type 'Function' does not satisfy the constraint 'new (...args: any) => any'.

ReturnType<Type>

Construct a new type from the return value type of the function type Type

example

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<Type>

Construct a new type from the instance type of the constructor type Type

example

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<Type>

Construct a type so that all attributes of Type required .
The opposite is Partial .

example

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

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

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

ThisParameterType<Type>

this parameter type from the function type.
If the function type does not contain the this parameter, it will return unknown type.

example

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

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

OmitThisParameter<Type>

From Type excluded types this parameters.
If the this is not declared, the result type is Type .
Otherwise, use the Type type to construct a type without the this parameter.
Generics will be ignored, and only the last overloaded signature will be used.

example

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

const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);

console.log(fiveToHex());

ThisType<Type>

This tool will not return a converted type.
It serves as a mark this
Note that if you want to use this type, you must enable --noImplicitThis .

example

// Compile with --noImplicitThis

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);

In the above example, makeObject parameters in the methods objects having a context type ThisType<D & M> , so methods method object in this type of { x: number, y: number } & { moveBy(dx: number, dy: number): number } .

In lib.d.ts , ThisType<T> identifies the interface as a simple empty interface declaration. Except for the context type that is recognized as an object literal, this interface is no different from a normal empty interface.



This article is a summary of the relevant content of the Ts Chinese document and is not original.


forceddd
271 声望912 粉丝

一名前端爱好者。