TypeScript 的 typeof 操作符

profile image

JavaScript 中的 typeof 操作符、其区别以及在 TypeScript 中的各种用途

本帖由 DeepL 翻译。如有任何翻译错误,请告知我们!

使用 TypeScript 时,您会经常遇到typeof操作符(JavaScript 中也有此操作符)。在 TypeScript 中,typeof在两种不同的上下文中使用。

  1. JavaScript 的运行时typeof操作符
  2. TypeScript 中作为类型操作符的typeof

1. JavaScript 的运行时 typeof 操作符

typeof返回一个字符串,表示操作数的数据类型。

jsx
 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也可以在类型上下文中使用。在这种情况下,它的作用有所不同

tsx
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只能用于从值中提取类型。如果在已经是类型的情况下使用它,就会出现错误。

tsx
// 不正确的使用
type MyString = string
type Wrong = typeof MyString; // 错误!

// 正确的用法
const myString = "hello"
type Correct = typeof myString; // string

利用 typeof

1. 从数组中提取联合类型

tsx
const colors = ["red", "green", "blue"] as const
type Colors = typeof colours[number];
// type Colors = "red" | "green" | "blue" 型

提取对象类型

tsx
// 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来提取函数的参数和返回类型。

tsx
函数 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;
// }

另请参见

❤️ 0
🔥 0
😎 0
⭐️ 0
🆒 0