[TypeScript] Query Properties with keyof and Lookup Types in TypeScript

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[TypeScript] Query Properties with keyof and Lookup Types in TypeScript相关的知识,希望对你有一定的参考价值。

The keyof operator produces a union type of all known, public property names of a given type. You can use it together with lookup types (aka indexed access types) to statically model dynamic property access in the type system.

 

interface Todo {
    id: number;
    text: string;
    completed: boolean;
  }

  const todo: Todo = {
    id: 1,
    text: "Buy milk",
    completed: false
  };

// K extends keyof T: K will be the unit types of ‘id‘, ‘text‘, ‘completed‘
// T[K] is the lookup tells the Typescript the correct return type
function prop<K extends keyof T, T>(key: K, obj: T): T[K] { 
    return obj[key];
}

const id = prop("id", todo);  // type number
const text = prop("text", todo); // type string
const completed = prop("completed", todo); // type boolean

console.log(id)
console.log(text)
console.log(completed)

 

以上是关于[TypeScript] Query Properties with keyof and Lookup Types in TypeScript的主要内容,如果未能解决你的问题,请参考以下文章

typescript 秋田layout.query.ts

typescript 秋田auth.query.ts

typescript movies.query.ts

typescript contacts.query.ts

typescript todos.query.ts

typescript posts7.query.ts