typescript中文变量-TypeScript 中的 Typeof 类型运算符

前言

TypeScript的官方文档已经更新,但是我能找到的英文文档仍然是旧版本。 因此,对一些新增和修订的章节进行了翻译和整理。

本文编译自《TypeScript 手册》中的“Typeof 类型运算符”章节。

本文并非严格按照原文翻译,部分内容也进行了解释和补充。

typeof 类型运算符(The typeof 类型运算符)

JavaScript 本身具有 typeof 运算符,您可以在表达式上下文中使用它:

<code class="hljs language-typescript" lang="typescript">// Prints "string"
console.log(typeof "Hello world");

TypeScript 添加的 typeof 方法可以在类型上下文(type context)中使用来获取变量或属性的类型。

typescript变量声明_typescript中文变量_变量中文命名

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

如果只是用来判断基本类型,自然用处不大,与其他类型运算符配合使用才能发挥它的作用。

举一个反例:比如用TypeScript内置的ReturnTypep。 您传入一个函数类型,ReturnTypep 返回该函数的返回值的类型:

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

如果我们直接在函数名上使用 ReturnType,我们将看到如下错误:

function f() {
  return { x: 10, y: 3 };
}
type P = ReturnType;
// 'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?

这是因为值和类型不是同一件事。 要获取值 f(即函数 f 的类型),我们需要使用 typeof:

typescript中文变量_变量中文命名_typescript变量声明

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

局限性

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

在 TypeScript 中,只有在标识符(例如变量名)或其属性上使用 typeof 才是合法的。 这可能会导致一些令人困惑的问题:

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

我们的初衷是获取msgbox的返回值的类型(“Are you sure you want to continue?”),所以直接使用了typeof msgbox(“Are you sure you want to continue?”),看起来还行通常,但并非如此,因为 typeof 只能用于标识符和属性。 正确的写法应该是:

ReturnType<typeof msgbox>

(注:原文到此结束)

在对象上使用 typeof

我们可以在对象上使用 typeof :

const person = { name: "kevin", age: "18" }
type Kevin = typeof person;
// type Kevin = {
// 		name: string;
// 		age: string;
// }

对函数使用 typeof

我们还可以在函数上使用 typeof:

function identity<Type>(arg: Type): Type {
  return arg;
}
type result = typeof identity;
// type result = (arg: Type) => Type

使用 typeof 进行枚举

在 TypeScript 中,enum 是一种新的数据类型,但在运行时,它会被编译成对象。

enum UserResponse {
  No = 0,
  Yes = 1,
}

对应编译后的JavaScript代码为:

var UserResponse;
(function (UserResponse) {
    UserResponse[UserResponse["No"] = 0] = "No";
    UserResponse[UserResponse["Yes"] = 1] = "Yes";
})(UserResponse || (UserResponse = {}));

如果我们复制 UserResponse:

console.log(UserResponse);
// [LOG]: {
//   "0": "No",
//   "1": "Yes",
//   "No": 0,
//   "Yes": 1
// } 

变量中文命名_typescript变量声明_typescript中文变量

如果我们对 UserResponse 使用 typeof:

type result = typeof UserResponse;
// ok
const a: result = {
      "No": 2,
      "Yes": 3
}
result 类型类似于:
// {
//	"No": number,
//  "YES": number
// }

然而,对于枚举类型仅使用 typeof 通常是没有用的。 通常与 keyof 运算符一起使用来获取属性名称的组合字符串:

type result = keyof typeof UserResponse;
// type result = "No" | "Yes"

TypeScript 家族

TypeScript系列文章由官方文档翻译、重难点解析、实用方法三部分组成,涵盖入门、进阶、实战。 旨在为您提供系统的TS学习教程。 整个系列预计40篇左右。 点击此处浏览全系列文章,建议顺便收藏本站。

微信:“mqyqingfeng”typescript中文变量,加我为世宇唯一读者群。

如果有错误或者不准确的地方,还请各位不吝赐教typescript中文变量,非常感谢。 如果你喜欢或者有启发,欢迎star,这也是对作者的鼓励。