Typeof 类型运算符

typeof 类型运算符

JavaScript 已经存在一个 typeof 运算符,你可以将其用于表达式上下文

ts
// Prints "string"
console.log(typeof "Hello world");
Try

TypeScript 增加了一个 typeof 运算符,你可以在类型上下文中使用它来引用变量或属性的类型

ts
let s = "hello";
let n: typeof s;
let n: string
Try

对于基本类型,这并没有太大用处,但结合其他类型运算符,你可以使用 typeof 来方便地表达许多模式。例如,我们先来看预定义的类型 ReturnType<T>。它接收一个函数类型并产生其返回类型

ts
type Predicate = (x: unknown) => boolean;
type K = ReturnType<Predicate>;
type K = boolean
Try

如果我们尝试在一个函数名上使用 ReturnType,我们会看到一个具有指导意义的错误

ts
function f() {
return { x: 10, y: 3 };
}
type P = ReturnType<f>;
'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?2749'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?
Try

请记住,类型不是一回事。要引用f 所具有的类型,我们使用 typeof

ts
function f() {
return { x: 10, y: 3 };
}
type P = ReturnType<typeof f>;
type P = { x: number; y: number; }
Try

限制

TypeScript 有意限制了你可以对哪些表达式使用 typeof

具体来说,仅允许对标识符(即变量名)或其属性使用 typeof。这有助于避免陷入误区,即编写了你以为正在执行但实际上并未执行的代码

ts
// Meant to use = ReturnType<typeof msgbox>
let shouldContinue: typeof msgbox("Are you sure you want to continue?");
',' expected.1005',' expected.
Try

TypeScript 文档是一个开源项目。通过 发送 Pull Request 帮助我们改进这些页面 ❤

此页面的贡献者
OTOrta Therox (4)
JLJimmy Liao (1)

最后更新:2026 年 3 月 27 日