2
头图

Preface

The official documentation of TypeScript has long been updated, but the Chinese documents I can find are still in the older version. Therefore, some new and revised chapters have been translated and sorted out.

This article is organized from the " Typeof Type Operator " chapter in the TypeScript Handbook.

This article does not strictly follow the original translation, but also explains and supplements part of the content.

typeof type operator (The typeof type operator)

JavaScript itself has the typeof operator, you can use it in the expression context:

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

typeof method added by TypeScript can be used in a type context to obtain the type of a variable or attribute.

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

If it is only used to judge the basic types, it is of little use. It can only be used in conjunction with other type operators to play its role.

For example: For example, with TypeScript built-in ReturnTypep<T> . You pass in a function type, ReturnTypep<T> will return the type of the return value of the function:

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

If we directly use ReturnType for a function name, we will see an error like this:

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'?

This is because values and types are not the same thing. In order to get the value f which is f , we need to use typeof :

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

Limitations

TypeScript intentionally limits the types of expressions typeof

In TypeScript, it is only legal to typeof for identifiers (such as variable names) or their attributes. This can lead to some confusing questions:

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

We originally intended to get the msgbox("Are you sure you want to continue?") of the return value of typeof msgbox("Are you sure you want to continue?") , which seems to be able to execute normally, but in fact it will not. This is because typeof can only be used for identifiers and attributes. The correct way of writing should be:

ReturnType<typeof msgbox>

(Note: The original text ends here)

typeof for the object

We can use typeof for an object:

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

// type Kevin = {
//         name: string;
//         age: string;
// }

typeof for the function

We can also use typeof for a function:

function identity<Type>(arg: Type): Type {
  return arg;
}

type result = typeof identity;
// type result = <Type>(arg: Type) => Type

typeof for enum

In TypeScript, enum is a new data type, but when it is run, it will be compiled into an object.

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

The corresponding compiled JavaScript code is:

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

If we print UserResponse :

console.log(UserResponse);

// [LOG]: {
//   "0": "No",
//   "1": "Yes",
//   "No": 0,
//   "Yes": 1
// } 

And if we UserResponse use typeof :

type result = typeof UserResponse;

// ok
const a: result = {
      "No": 2,
      "Yes": 3
}

result 类型类似于:

// {
//    "No": number,
//  "YES": number
// }

However, it is generally useless to use typeof for an enum type keyof operator to obtain the union string of the attribute name:

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

TypeScript series

The TypeScript series of articles consists of three parts: official document translation, important and difficult analysis, and practical skills. It covers entry, advanced, and actual combat. It aims to provide you with a systematic learning TS tutorial. The entire series is expected to be about 40 articles. Click here to browse the full series of articles, and suggest to bookmark the site by the way.

WeChat: "mqyqingfeng", add me to the only reader group in Kongyu.

If there are mistakes or not rigorous, please correct me, thank you very much. If you like or have some inspiration, star is welcome, which is also an encouragement to the author.


冴羽
9.3k 声望6.3k 粉丝

17 年开始写前端文章,至今 6 个系列,上百篇文章,全网千万阅读