typeof 类型运算符
JavaScript 已经存在一个 typeof 运算符,你可以将其用于表达式上下文
tsTry// Prints "string"console .log (typeof "Hello world");
TypeScript 增加了一个 typeof 运算符,你可以在类型上下文中使用它来引用变量或属性的类型
tsTrylets = "hello";letn : typeofs ;
对于基本类型,这并没有太大用处,但结合其他类型运算符,你可以使用 typeof 来方便地表达许多模式。例如,我们先来看预定义的类型 ReturnType<T>。它接收一个函数类型并产生其返回类型
tsTrytypePredicate = (x : unknown) => boolean;typeK =ReturnType <Predicate >;
如果我们尝试在一个函数名上使用 ReturnType,我们会看到一个具有指导意义的错误
tsTryfunctionf () {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
tsTryfunctionf () {return {x : 10,y : 3 };}typeP =ReturnType <typeoff >;
限制
TypeScript 有意限制了你可以对哪些表达式使用 typeof。
具体来说,仅允许对标识符(即变量名)或其属性使用 typeof。这有助于避免陷入误区,即编写了你以为正在执行但实际上并未执行的代码
tsTry// Meant to use = ReturnType<typeof msgbox>let',' expected.1005',' expected.shouldContinue : typeofmsgbox ( "Are you sure you want to continue?");