TypeScript高级语法
在线运行 TypeScript https://www.typescriptlang.org/play
typeof
typeof val
获取对象的类型
- 已知一个 javascript 变量,通过 typeof 就能直接获取其类型
const str = 'foo'
typeof str === 'string' // true
const user = {
name: 'IanaIO',
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
获取 T 类型中的所有 key,类似与 Object.keys(object)
根据 key 获取对象其属性的例子
function getProperty<T extends object, K extends keyof T>(obj: T, key: K) {
return obj[key]
}
上面代码有很好的代码提示,并且如果获取的 key 不在其对象中,将会直接报错。
对于一些常用类型的 keyof 值
type K0 = keyof string
// number | typeof Symbol.iterator | "toString" | "charAt" | ... more
type K1 = keyof boolean
// "valueOf"
type K2 = keyof number
// "toString" | "valueOf" | "toFixed" | "toExponential" | "toPrecision" | "toLocaleString"
type K3 = keyof any
// string | number | symbol