myml / myml.github.io

myml的个人网站
https://myml.dev
3 stars 0 forks source link

typescript 常用泛型 #22

Open myml opened 5 years ago

myml commented 5 years ago

预定义对象

class Test {
    a: string;
    b: number;
    c() {}
}

类型为对象键名

type ObjectKey<T> = keyof T  

 ObjectKey<Test> = 'a' | 'b' | 'c'  

类型为对象属性类型

type ObjectValue<T> = T[keyof T] 

ObjectValue<Test> = string | number | (() => void)  

转换对象属性为可选

type ObjectPartial<T> = { [K in keyof T]?: T[K] };  

ObjectPartial<Test> =  
    class Test {
        a?: string;
        b?: number;
        c?() {}
    }

去除对象属性

type ObjectDelete<T, D extends keyof T> = { [K in Exclude<keyof T, D>]: T[K] };

ObjectDelete<Test> =  
    class Test {
        b: number;
        c() {}
    }

用对象属性类型过滤属性

type ObjectKeyFilterByValue<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];

例子

ObjectKeyFilterByValue<Test,string> = { a: string }