zoukankan      html  css  js  c++  java
  • [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.

    Take away:

    1. extends

    2. keyof 

    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<T, K extends keyof T>(obj: T, key: K): T[K] {
        return obj[key];
    }
    
    type TodoId = Todo['id'];
    type TodoText = Todo['text'];
    type TodoCompleted = Todo['completed'];
    
    const id: TodoId = prop(todo, 'id'); // type number
    const text: TodoText = prop(todo, 'text'); // type string
    const completed: TodoCompleted = prop(todo, 'completed'); // type boolean
  • 相关阅读:
    jQuery-选择器及属性修改
    jQuery 基础理论
    CSS 之 BFC(块级格式化上下文)
    H5--Web Storage
    H5 -WebWorker
    H5 --拖放
    nodejs Multer中间件
    k8s pod
    kubernetes
    优化CUDA数据传输
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7828347.html
Copyright © 2011-2022 走看看