typeof
类型运算符
¥The typeof
type operator
JavaScript 已经有一个可以在表达式上下文中使用的 typeof
运算符:
¥JavaScript already has a typeof
operator you can use in an expression context:
tsTry
// Prints "string"console .log (typeof "Hello world");
TypeScript 添加了一个 typeof
运算符,你可以在类型上下文中使用它来引用变量或属性的类型:
¥TypeScript adds a typeof
operator you can use in a type context to refer to the type of a variable or property:
tsTry
lets = "hello";letn : typeofs ;
这对于基本类型不是很有用,但结合其他类型运算符,你可以使用 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:
tsTry
typePredicate = (x : unknown) => boolean;typeK =ReturnType <Predicate >;
如果我们尝试在函数名上使用 ReturnType
,我们会看到一个指导性错误:
¥If we try to use ReturnType
on a function name, we see an instructive error:
tsTry
functionf () {return {x : 10,y : 3 };}type'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'?P =ReturnType <>; f
请记住,值和类型不是一回事。要引用值 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
:
tsTry
functionf () {return {x : 10,y : 3 };}typeP =ReturnType <typeoff >;
限制
¥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:
tsTry
// Meant to use = ReturnType<typeof msgbox>let',' expected.1005',' expected.shouldContinue : typeofmsgbox ( "Are you sure you want to continue?");