Ts泛型工具类

目录

partial

Readonly

Pick

Record


partial

作用:将所有属性设置为可选类型 

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

type PartialProps = Partial<Props>

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

 Readonly

作用:将所有的属性设置为只读

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> 从Type中选择一组属性来构造新类型

在第二个类型变量里面要是没有传入的话,使用的时候会报错

 正确传入则可以正常使用

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>创建一个对象类型,属性键是Keys, 属性值是Type 

Record需要传入两个参数,1、表示对象有哪些属性 2、表示属性的类型是什么

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

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

没有传入对应的类型就会报错

猜你喜欢

转载自blog.csdn.net/weixin_48329823/article/details/128308050