typeof 类型运算符

typeof 类型运算符

¥The typeof type operator

JavaScript 已经有一个可以在表达式上下文中使用的 typeof 运算符:

¥JavaScript already has a typeof operator you can use in an expression context:

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

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

¥TypeScript adds a typeof operator you can use in a type context to refer to the type of a variable or property:

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

这对于基本类型不是很有用,但结合其他类型运算符,你可以使用 typeof 方便地表达许多模式。例如,让我们从查看预定义类型 ReturnType<T> 开始。它接受一个函数类型并产生它的返回类型:

¥This isn’t very useful for basic types, but combined with other type operators, you can use typeof to conveniently express many patterns. For an example, let’s start by looking at the predefined type ReturnType<T>. It takes a function type and produces its return type:

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

如果我们尝试在函数名上使用 ReturnType,我们会看到一个指导性错误:

¥If we try to use ReturnType on a function name, we see an instructive error:

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

¥Remember that values and types aren’t the same thing. To refer to the type that the value f has, we use typeof:

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

限制

¥Limitations

TypeScript 有意限制你可以使用 typeof 的表达式类型。

¥TypeScript intentionally limits the sorts of expressions you can use typeof on.

具体来说,在标识符(即变量名)或其属性上使用 typeof 是唯一合法的。这有助于避免编写你认为正在执行但不是的代码的混乱陷阱:

¥Specifically, it’s only legal to use typeof on identifiers (i.e. variable names) or their properties. This helps avoid the confusing trap of writing code you think is executing, but isn’t:

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