typeof 类型运算符

typeof 类型运算符

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

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

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

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

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

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

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

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

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

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

限制

r61x/lftDHmkHKWBRUTtfbC/Pd8ZbCqKB4w6oDZON+AWMND69M10jUUR+M6lrpNllA+sIL+7Hv4qx1lsUDfzmi6OjPXczu0oITD5+7TxRJFYeFGeoIhRZaxlvT7hcTbK

nXACKLZHwJyl0yvoQ6a2/c0Tmbw7JLvK/INuROOHoFwiPIc/FcSzdJsEo9lI0b1LI56+7MgZfLa2eYL90c1nBXzInRheqJP+/TcdSCs4gLy81gZIOGdCVrHnJQ0qW+3up+phVEovR2WXinK/UZ/jd+RgI3f8E+XrOPLRD2+VHqFUFxUem3wRG5pQ9crZn1w5ZtcNphbyOx3AADVREtil//AZWH5lymt61DY7fGSS2bXt7jYbZ3PSWX06/FgeZWV3

declare const msgbox: () => boolean;
// type msgbox = any;
// Meant to use = ReturnType<typeof msgbox>
let shouldContinue: typeof msgbox("Are you sure you want to continue?");