TypeScript高级语法
在线运行 TypeScript https://www.typescriptlang.org/play
typeof
typeof val
获取对象的类型
- 已知一个 javascript 变量,通过 typeof 就能直接获取其类型
const str = 'foo'
typeof str === 'string' // true
const user = {
name: 'xujianlei',
age: 12,
address: {
province: '福建',
city: '厦门',
},
}
type User = typeof user
// {
// name: string;
// age: number;
// address: {
// province: string;
// city: string;
// };
// }
type Address = (typeof user)['address']
// {
// province: string;
// city: string;
// }
- 获取函数的类型(参数类型与返回值类型)
function add(a: number, b: number): number {
return a + b
}
type AddType = typeof add
// (a: number, b: number) => number
type AddReturnType = ReturnType<typeof add>
// number
type AddParameterType = Parameters<typeof add>
// [a: number, b: number]
keyof
keyof T