Keyof 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”Keyof Type Operator“Chapter.

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

keyofType operator

Use for an object typekeyofOperator, it will return a string composed of the property name of the object or the union of numeric literals. In this example, type P is equivalent to “X” | “Y”:

type Point = { x: number; y: number };
type P = keyof Point;

// type P = keyof Point

But if this type has onestringperhapsnumberIndex signature of type,keyofThese types will be returned directly:

type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish;
// type A = number

type Mapish = { [k: string]: boolean };
type M = keyof Mapish;
// type M = string | number

Note that in this example,Myesstring | numberThis is because the property name of the JavaScript object will be forced to a stringobj[0]andobj["0"]It’s the same.

(Note: the original text ends here)

Numeric literal union type

As we said at the beginning,keyofIt is also possible to return a numeric literal union type. When will the numeric literal union type be returned? We can try to build such an object:

const NumericObject = {
  [1] : "YU-1",
  [2] : "Yu II",
  [3] : "Yu 3"

type result = keyof typeof NumericObject

//The result of typeof numbericobject is:
// {
//   1: string;
//   2: string;
//   3: string;
// }
//So the final result is:
// type result = 1 | 2 | 3


In fact, typescript can also support attribute names of symbol type:

const sym1 = Symbol();
const sym2 = Symbol();
const sym3 = Symbol();

const symbolToNumberMap = {
  [sym1]: 1,
  [sym2]: 2,
  [sym3]: 3,

type KS = keyof typeof symbolToNumberMap; // typeof sym1 | typeof sym2 | typeof sym3

This is why when we use it in generics like the following example, we will report an error like this:

function useKey<T, K extends keyof T>(o: T, k: K) {
  var name: string = k; 
  // Type 'string | number | symbol' is not assignable to type 'string'.

If you are sure to use only string type attribute names, you can write as follows:

function useKey<T, K extends Extract<keyof T, string>>(o: T, k: K) {
  var name: string = k; // OK

If you want to handle all attribute names, you can write this:

function useKey<T, K extends keyof T>(o: T, k: K) {
  var name: string | number | symbol = k;

Classes and interfaces

Use for classkeyof

//Example 1
class Person {
  Name: "Yu Yu"

type result = keyof Person;
// type result = "name"
//Example 2
class Person {
  [1] : String = "冴 feather";

type result = keyof Person;
// type result = 1

Use of interfaceskeyof

interface Person {
  name: "string";

type result = keyof Person;
// type result = "name"

actual combat

InGeneric of typescript“There is one in this articlekeyofApplication of:

We want to get the value of a given property name of an object, so we need to make sure we don’t get itobjProperty that does not exist on. So we establish a constraint between the two types:

function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) {
  return obj[key];
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a");
getProperty(x, "m");

// Argument of type '"m"' is not assignable to parameter of type '"a" | "b" | "c" | "d"'.

In the backMappred Types“We will also talk aboutkeyof

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.

Recommended Today

MySQL team development specification

Database object naming convention Database object Database objects are part of a database. The common ones are the following: table, index, view, diagram, default, rule, trigger, stored procedure, user, etc. Naming conventions refer to naming conventions for database objects such as schema, table, index, and constraints. Global naming conventions for database objects 1. The naming […]