TypeScript 学习指南 Part 4-6-4 Handbook Type Manipulation 4

639 阅读1分钟

Typeof Type Operator

Thetypeoftype operator

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

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

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

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

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 (TS预定义好的)type ReturnType<T>. It takes a function type and produces its return type:

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

If we try to use ReturnType on a function name, we see an instructive(有益的) error:

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'?'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?Try

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

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

Limitations 限制

TypeScript intentionally(故意;有意地;蓄意地) limits(限制) the sorts of expressions you can use typeof on.

TypeScript 有意的限制了可以使用 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:

特别地,只有对标识符(比如变量名)或者他们的属性,使用 typeof 才是合法的。这有助于避免编写您认为正在执行的代码时出现的令人困惑的陷阱,但是没有:

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

参考翻译

segmentfault.com/a/119000004…