本篇整理自 TypeScript Handbook 中 「Typeof Type Operator」 章节。
typeof
JavaScript 本身就有 typeof 操作符,你可以在表达式上下文中使用:
// Prints "string"
console.log(typeof "Hello world");
而 TypeScript 添加的 typeof 方法可以在类型上下文中使用,用于获取一个变量或者属性的类型
function f() {
return { x: 10, y: 3 };
}
type P = ReturnType<typeof f>;
// type P = {
// x: number;
// y: number;
// }
使用场景: 比如搭配 TypeScript 内置的 ReturnTypep<T>。你传入一个函数类型,ReturnTypep<T> 会返回该函数的返回值的类型
type Predicate = (x: unknown) => boolean;
type K = ReturnType<Predicate>;
/// type K = boolean
限制
TypeScript 有意的限制了可以使用 typeof 的表达式的种类。
在 TypeScript 中, typeof 只能对标识符和属性使用。
let foo: typeof console.log("Are you sure you want to continue?");
// error ---> ',' expected.
应该修改为
let foo: ReturnType<typeof console.log>; // type foo = void
对常见类型使用typeof
对象
const person = { name: "kevin", age: "18" }
type Kevin = typeof person;
// type Kevin = {
// name: string;
// age: string;
// }
函数
function identity<Type>(arg: Type): Type {
return arg;
}
type result = typeof identity;
// type result = <Type>(arg: Type) => Type
枚举
enum UserResponse {
No = 0,
Yes = 1,
}
type result = typeof UserResponse;
// result 类型类似于:
// {
// "No": number,
// "YES": number
// }
type keys = keyof typeof UserResponse;
// type keys = 'YES' | 'NO'