An introduction to

keyof

Take an Object and generate the union of the string key of the Object.

  • For common objects:
type Point = { x: number; y: number };
type P = keyof Point; / / p value for 'x' | 'y'
const a:P = 'x'; 
const b:P = 1;  //Type '1' is not assignable to type 'keyof Point'.ts(2322)
Copy the code
  • For index signature objects:
type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish; // type A = numbertype Mapish = { [k: string] :boolean };
type M = keyof Mapish; // type M = string | number 
The reason M can be number is that in the index signature of an object, number is forced to be converted to string, as in the example below referencing Mapish
const mapist: Mapish = {}
mapist[1] = false;
mapist['a'] = true;
Copy the code
  • For enumeration types
enum Colors {
    red,
    blue,
    yellow
}
type A = keyof Colors; // "toString" | "toFixed" | "toExponential" | "toPrecision" | "valueOf" | "toLocaleString"
// When keyof is used on an enum of type number, you get the combined type of the method name (in string format) defined on number.prototype.
enum Colors {
    red = 'red',
    blue = 'blue',
    yellow = 'yellow'
}
type A = keyof Colors; // number | "toString" | "charAt" | "charCodeAt" | "concat" | ... 27 more... | "padEnd"
// When keyof is applied to enum of type string, we get a combined type of number plus the names of all the methods defined on String.prototype.
Copy the code

typeof

In JS syntax, typeof is the fetch type, and in TS application is like converting JS syntax to TS syntax

In the following demo, A equals type A = {x: number; y: number; }

const obj = { x: 10.y: 3 }
type A = typeof obj;
const a: A = {
    x:1.y:1
}
Copy the code

Combination with ReturnType:

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

Indexed Access Types

Indexed Access Types, one of the special uses is to index arrays by number. I’ve been looking for an accurate translation of Indexed Access Types, and ended up with Indexed Access Types, if you have a good translation, feel free to leave a comment in the comments section

type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"]; //type Age = number
type I2 = Person[keyof Person];//type I2 = string | number | boolean
Copy the code

If the array object is indexed by “number”, it is similar to union, that is, by or joining all types. Note that the array traversed by “number” is js syntax, which must be converted to TS via typeof before it can be defined in type

const MyArray = [
    { name: "Alice".age: 15 },
    { name: "Bob".age: 23 },
    { name: "Eve".age: 38 },
    { name: 'Oli'.age: 22.sex: 'M'}];type Person = typeof MyArray[number]; //type Person = { name: string; age: number; sex? : undefined; } | { name: string; age: number; sex: string; }
const p1: Person = { name: 'lin'.age: 15 }
const p2: Person = { name: 'lin'.age: 15.sex: 'F'}
Copy the code