Typescript語法積累

Typescript讓Js這個超弱類型的語言編寫更加嚴格。javascript

索引訪問類型

Typescript中如何索引屬性值呢?從typescript2.1開始支持mapped-types。 js中獲取一個屬性值的方式很是簡單:java

function prop(obj, key) {
    return obj[key];
}
複製代碼

而在typescript中,若是咱們以下的設置,那麼獲得的屬性值類型就是any。typescript沒有辦法知道內部類型。typescript

function prop(obj: {}, key: string) {
    return obj[key];
}

const todo ={
    id: 1,
    text: 'Buy',
    due: new Date(2019,8,1)
};
const id = prop(todo, "any"); // type will be any

複製代碼

因而乎keyof操做應運而生,keyof會搜索對象中全部的key。keyof獲得的是keys而值對應的類型T[keyof T],官方文檔中的例子:bash

function getProperty<T, K extends keyof T>(obj: T, key: K) {
    return obj[key];
}
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]) {
    obj[key]= value;
}

let x = { foo: 10, bar: "hello!" };

let foo = getProperty(x, "foo"); // number
let bar = getProperty(x, "bar"); // string

let oops = getProperty(x, "wargarbl"); // Error! "wargarbl" is not "foo" | "bar"

setProperty(x, "foo", "string"); // Error!, string expected number

複製代碼

Mapped Typesapp

interface IState {
    pending: string,
    started: string;
    completed: string;
    id: number;
}
type stateKeys = keyof IState; // "pending"|"started"|"completed"|"id"

// how to get value by property
const Inital_State: IState = {
    pending: 'pending',
    stared: 'started',
    completed: 'string',
    id: 0
};
const obj : { [key in stateKeys]: IState[key]} = {...} ;

function prop<T, K extends keyof T>(obj: T, key: K) {
    return obj[key];
}
const id = prop(Inital_State, "id"); // number 
複製代碼

關於Objecg.entrie()是如何定義type的oop

interface ObjectConstructor {
    // ...
    entries<T extends {[key:string] : any}, K extends keyof T>(o:T):[keyof T, T[K]][];
    // ...
}

複製代碼
相關文章
相關標籤/搜索