码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-11-13 23:24:18      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:mil   use   produces   complete   console   interface   type   dex   public   

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

标签:mil   use   produces   complete   console   interface   type   dex   public   

原文地址:http://www.cnblogs.com/Answer1215/p/7828347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!