Typeof type operator of typescript



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

This article is compiled from “typescript Handbook”Typeof Type Operator“Chapter.

This article is not translated strictly according to the original text, and some contents are explained and supplemented.

typeofType operator (thetypeof type operator)

JavaScript itself hastypeofOperator, you can use in the expression context:

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

Typescript addstypeofMethod can be used in 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 type, it is naturally of little use. It can play its role only when it is used with other type operators.

For example: for example, with typescript built-inReturnTypep<T>。 You pass in a function type,ReturnTypep<T>The type of return value of this function will be returned:

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

If we use a function name directlyReturnType, we will see such an error report:

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. To get the valuefThat is, functionfWe need to usetypeof

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


Typescript intentionally limits its usetypeofType of expression.

In typescript, only identifiers (such as variable names) or their attributes are usedtypeofIt’s legal. 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 meant to getmsgbox("Are you sure you want to continue?")The type of the return value of, so it is used directlytypeof msgbox("Are you sure you want to continue?"), it seems that it can be executed normally, but it doesn’t. this is becausetypeofCan only be used with identifiers and attributes. The correct wording should be:

ReturnType<typeof msgbox>

(Note: the original text ends here)

Use on objectstypeof

We can use it on an objecttypeof

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

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

Use for functionstypeof

We can also use for a functiontypeof

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

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

Use of enumtypeof

In typescript, enum is a new data type, but it will be compiled into objects when running.

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 itUserResponse


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

And if we’re rightUserResponseusetypeof

type result = typeof UserResponse;

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

The result type is similar to:

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

However, only one enum type is usedtypeofIt’s generally useless. It’s usually matchedkeyofOperator to get the union string of the attribute name:

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

Typescript series

Typescript series articles are composed of three parts: official document translation, key and difficult point analysis and practical skills, covering introduction, advanced and practical combat. It aims to provide you with a tutorial for systematically learning ts. the whole series is expected to be about 40.Click here to browse the full series of articles and suggest collecting sites by the way.

Wechat: “mqyqingfeng”, add me to Yu Yu’s only reader group.

If there is any mistake or lack of preciseness, please be sure to correct it. Thank you very much. If you like it or have some inspiration, welcome star, which is also an encouragement to the author.