使用 TypeScript 时,您会经常遇到typeof
操作符(JavaScript 中也有此操作符)。在 TypeScript 中,typeof
在两种不同的上下文中使用。
- JavaScript 的运行时
typeof
操作符 - TypeScript 中作为类型操作符的
typeof
1. JavaScript 的运行时 typeof 操作符
typeof
返回一个字符串,表示操作数的数据类型。
让 value = "hello";
console.log(typeof value); // "string"(字符串
让 number = 32;
console.log(typeof number); // "数字"
let func = () => {};
console.log(typeof func); // "函数"
返回值是 JavaScript 的基本数据类型(布尔、数字、大整数、字符串、符号、空、未定义)以及函数和对象。
2 TypeScript 的类型操作符 typeof
在 TypeScript 中,typeof
也可以在类型
上下文中使用。在这种情况下,它的作用有所不同
const user = {
name: "John"、
age: 30、
isAdmin: true
};
const v_user = typeof user; // 对象
type User = typeof user;
// 结果:
// type User = {
// name: string;
// age: number;
// isAdmin: boolean;
// }
在上面的示例中,v_user
是一个使用const
关键字声明的变量。因此,需要给它赋值,所以它返回"object"
,表示user 的
运行时类型。然而,在type
关键字之后使用的typeof
会返回 typescript 的类型。
Typeof
只能用于从值中提取类型。如果在已经是类型的情况下使用它,就会出现错误。
// 不正确的使用
type MyString = string;
type Wrong = typeof MyString; // 错误!
// 正确的用法
const myString = "hello";
type Correct = typeof myString; // string
利用 typeof
1. 从数组中提取联合类型
const colors = ["red", "green", "blue"] as const;
type Colors = typeof colours[number];
// type Colors = "red" | "green" | "blue" 型
提取对象类型
// without as const
const config = {
endpoint: "api.example.com"、
端口:3000
};
type Config = typeof config;
// type Config = {
// endpoint: string;
// port: number;
// }
// 以 const
const config = {
endpoint: "api.example.com"、
port: 3000
} as const;
type Config = typeof config;
// type Config = {
// readonly endpoint: "api.example.com";
// readonly port: 3000;
// }
当使用as const 时
,readonly
会被附加并提取出来。
3 提取函数类型
您可以使用实用程序类型ReturnType 和
Parameters
来提取函数的参数和返回类型。
函数 createUser(name: string, age: number) {
return { id: Date.now(), name, age };
}
// return { type User = ReturnType<typeof createUser>;
// type User = {
// id: number;
// name: string;
// age: number;
// }
// type Param = Parameters<typeof createUser> 类型参数
// 类型参数 = {
// name: string;
// age: number;
// }
另请参见