Ts generic tool class

Table of contents

partial

Readonly

Pick

Record


partial

Role: set all attributes to optional type 

interface Props {
    name: string,
    children: number[]
}

type PartialProps = Partial<Props>

let obj: PartialProps = {
    name: '111',
    children: [1,2,3]
}

 Readonly

Role: set all properties to read-only

interface Props {
    name: string,
    children: number[]
}

type PartialProps = Readonly<Props>

let obj: PartialProps = {
    name: '111',
    children: [1,2,3]
}

obj.name = '222'

 Pick

Pick<Type, Keys> selects a set of properties from Type to construct a new type

If there is no input in the second type variable, an error will be reported when using it

 It can be used normally if it is passed in correctly

interface Props {
    id: number,
    name: string,
    children: number[]
}

type PartialProps = Pick<Props, 'id' | 'name'>

let obj: PartialProps = {
    id: 18,
    name: '111'
}

Record

Record<Keys, Type> creates an object type, the attribute key is Keys, and the attribute value is Type 

Record needs to pass in two parameters, 1. Which attributes the object has; 2. What is the type of the attribute

type RecordObj = Record<'a' | 'b' | 'c', number[]>

let obj: RecordObj = {
    a: [1,2,3],
    b: [1,2,3],
    c: [1,2,3],
}

If the corresponding type is not passed in, an error will be reported

Guess you like

Origin blog.csdn.net/weixin_48329823/article/details/128308050