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]][];
    // ...
}

复制代码
相关文章
相关标签/搜索