This is the fourteenth day of my participation in Gwen Challenge

It is common in development to get the values of some properties from an object and then build a collection

Chestnut, getValue function

Extract the values of an OBj object to form an array

let obj = {
  a: 1.b: 2.c: 3};function getValue(obj: any, keys: string[]) {
  return keys.map((key) = > obj[key]);
}
// print out [1,3]
console.log(getValue(obj, ["a"."c"]));
// ts will not error and print [undefined,undefined]
console.log(getValue(obj, ["e"."f"]));
Copy the code

Query operator

Keyof T represents the literal union type of all common attributes of type T

interface Obj {
  a: number;
  b: string;
}
/ / type inference to let key: "a" | "b"
let key: keyof Obj;
Copy the code

Index access operator

T[K] represents the type represented by the attribute K of object T

// Let value: number
let value: Obj["a"];
Copy the code

Generic constraint

T extends U means that a generic variable can inherit from certain types to obtain certain properties

The getValue function is modified

Requirement: The elements in keys must be attributes in obj

Define a generic variable T to constrain obj, define a generic variable K to constrain keys, add a type constraint to key of keys, that is, let K inherit the joint type of all obj attributes, return value of function, first an array, array element of type K corresponding type

let obj = {
  a: 1.b: 2.c: 3};function getValue<T.K extends keyof T> (obj: T, keys: K[]) :T[K] []{
  return keys.map((key) = > obj[key]);
}

console.log(getValue(obj, ["a"."c"]));
/ * will not type "" e" assigned to "type" "a" | | "c" "b" ". * /
console.log(getValue(obj, ["e"."f"]));
Copy the code

conclusion

Index types allow you to query and access object properties, and then, in conjunction with generic constraints, allow you to establish constraint relationships between objects, object properties, and property values