Typeof Type Operator of TypeScript

Keywords: Javascript Front-end html5 TypeScript

preface

The official documents of TypeScript have already 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.

The typeof type operator

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

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

The typeof method added by TypeScript 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, with the built-in returntypep < T > of TypeScript. If 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:

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 obtain the value f, that is, the type of function 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 that can use typeof.

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

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

We intended to get the type of the return value of msgbox("Are you sure you want to continue?"), so we directly used typeof msgbox("Are you sure you want to continue?"). It seems that it can be executed normally, but it won't. this is because typeof can only be used for identifiers and attributes. The correct wording should be:

ReturnType<typeof msgbox>

(Note: the original text ends here)

Use typeof on objects

We can use typeof for an object:

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

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

Use typeof for functions

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

Use typeof for enum

In TypeScript, enum is a new data type, but it will be compiled into an object 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 the UserResponse:

console.log(UserResponse);

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

And if we use typeof for UserResponse:

type result = typeof UserResponse;

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

result The type is similar to:

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

However, it is generally useless to only use typeof for an enum type. It is usually used with the keyof operator to obtain the joint string of attribute names:

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

TypeScript series

  1. Narrowing of TypeScript
  2. More on Functions of TypeScript
  3. Object Type of TypeScript
  4. Generics of TypeScript
  5. Keyof Type Operator of TypeScript

If you have any confusion about what TypeScript or other contents you want to know, please contact me. WeChat: mqyqingfeng, official account search: yayujs or JavaScript blog.

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.

Posted by asmon on Wed, 24 Nov 2021 05:32:07 -0800