preface

The official TypeScript documentation has been updated for a long time, but the Chinese documentation I could find was still in older versions. Therefore, some new and revised chapters are translated and sorted out.

This article is adapted from the TypeScript Handbook chapter “Typeof Type Operator”.

This paper does not strictly follow the translation of the original text, and some of the content has also been explained and supplemented.

typeofThe type operator (ThetypeofThe type operator)

JavaScript already has typeof operators, which you can use in expression contexts:

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

TypeScript adds Typeof methods that can be used in a type context to get the typeof a variable or property.

let s = "hello";
let n: typeof s;
// let n: string
Copy the code

It’s not much use if it’s just for basic types, but it’s useful when used in conjunction with other type operators.

For example, with TypeScript’s built-in ReturnTypep

. You pass in a function type, and ReturnTypep

returns the type of the function’s return value:

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

If we use ReturnType directly on a function name, we get 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'?
Copy the code

This is because values and types are not the same thing. To get the value f, the typeof 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;
// }
Copy the code

Limitations

TypeScript intentionally limits the kinds of expressions that can be used with Typeof.

In TypeScript, typeof is legal only 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.
Copy the code

We intended to get the MSgBox (“Are you sure you want to continue? ), so typeof msgbox(“Are you sure you want to continue? ), looks like it works, but it doesn’t, because Typeof can only be used for identifiers and attributes. The correct way to write this is:

ReturnType<typeof msgbox>
Copy the code

(Note: the original text ends here)

Using objectstypeof

We can use typeof on an object:

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

// type Kevin = {
// name: string;
// age: string;
// }
Copy the code

Use with functionstypeof

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
Copy the code

Use of enumtypeof

Enum is a new data type in TypeScript, but it is compiled into objects at runtime.

enum UserResponse {
  No = 0,
  Yes = 1,}Copy the code

The corresponding compiled JavaScript code is:

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

If we print UserResponse:

console.log(UserResponse);

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

And if we use typeof for UserResponse:

type result = typeof UserResponse;

// ok
const a: result = {
      "No": 2."Yes": 3} result is of type similar to:/ / {
//	"No": number,
// "YES": number
// }
Copy the code

However, using typeof alone for an enum type is generally useless, and is usually accompanied by the keyof operator to get the associative string for the attribute name:

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

The TypeScript series

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

If you are confused about TypeScript or want to know more about TypeScript, feel free to contact me on wechat: “mqyqingfeng”, search for “Yayujs” or “Yui’s JavaScript blog”.

If there is any mistake or not precise place, please be sure to give correction, thank you very much. If you like or are inspired by it, welcome star and encourage the author.