TS一些不常用但是有用的用法

1.利用keyof将某个interface里的索引全部变为只读,不允许修改(或者全部变为可选/必有)

interface Person {
name?: string
age: number
gender: number
}
// 只读
type ReadOnlyType = {
readonly [P in keyof T]: T[P]
}
// 可选
type ReadOnlyType = {
[P in keyof T]?: T[P]
}

// 必有
type ReadOnlyType = {
[P in keyof T]-?: T[P]
}

type ReadOnlyPerson = ReadOnlyType
// 只读
// type ReadOnlyPerson = {
// readonly name?: string

TS一些不常用但是有用的用法最先出现在Python成神之路

版权声明:
作者:主机优惠
链接:https://www.techfm.club/p/26013.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>