- 对于对象
如果对象嵌套层级比较深,我们手动定义ts类型会很复杂
const lo = {
name: 'ff',
age: 18,
address: {
province: '中国'
}
}
type Person = typeof lo
等价于
type Person = {
name: string
age: number
address: {
province: string
}
}
- 配合 keyof 获取所有枚举属性名
enum HttpMethod {
Get,
Post
}
const method: typeof HttpMethod = {
Get: 0,
Post: 1,
}
type Method = keyof typeof HttpMethod
// "Get" | "Post"
- 获取函数的类型
function add(a: number, b: number) {
return a + b
}
type AddType = typeof add // (a: number, b: number) => number
// 获取函数返回值类型
type AddReturnType = ReturnType<AddType> // number
// 获取函数参数类型
type AddParamsType = Parameters<AddType> // [a: number, b: number]
- 配合 as const 获取更精确的类型
let user = {
id: 666,
name: "发发"
} as const
type User = typeof user
// {readonly id: 666, readonly name: '发发'}
网友评论