TypeScript 的 typeof 运算符

profile image

typeof 运算符在 JavaScript 和 TypeScript 上下文中的差异及其各种用法

本帖由 Jetbrains's Coding Agent Junie junie logo翻译。如有任何翻译错误,请告知我们!

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

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

1. JavaScript 的运行时 typeof 运算符

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

jsx
let value = "hello";
console.log(typeof value); // "string"

let number = 32;
console.log(typeof number); // "number"

let func = () => {};
console.log(typeof func); // "function"

返回值是 JavaScript 的基本数据类型(boolean, number, bigint, string, symbol, null, undefined)以及 function 和 object。

2. TypeScript 的类型运算符 typeof

在 TypeScript 中,typeof 也可以在 type 上下文中使用。在这种情况下,它的作用有所不同。

tsx
const user = {
  name: "John",
  age: 30,
  isAdmin: true
};

const v_user = typeof user; // object
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 colors[number];
// type Colors = "red" | "green" | "blue"

2. 提取对象类型

tsx
// 不使用 as const
const config = {
  endpoint: "api.example.com",
  port: 3000
};
type Config = typeof config;
// type Config = {
//   endpoint: string;
//   port: number;
// }

// 使用 as 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. 提取函数类型

您可以使用工具类型 ReturnTypeParameters 来提取函数的参数和返回类型。

tsx
function createUser(name: string, age: number) {
  return { id: Date.now(), name, age };
}

type User = ReturnType<typeof createUser>;
// type User = {
//   id: number;
//   name: string;
//   age: number;
// }

type Param = Parameters<typeof createUser>
// type Param = {
//   name: string;
//   age: number;
// }

🔎 参考

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