TypeScript keyof returning specific type

后端 未结 1 973
暖寄归人
暖寄归人 2020-12-06 04:32

If I have the following type

interface Foo {
    bar: string;
    baz: number;
    qux: string;
}

can I use typeof to type a p

相关标签:
1条回答
  • 2020-12-06 05:14

    You can use conditional types in Tyepscript 2.8 :

    type KeysOfType<T, TProp> = { [P in keyof T]: T[P] extends TProp? P : never }[keyof T];
    
    let onlyStrings: KeysOfType<Foo, string>;
    onlyStrings = 'baz' // error
    onlyStrings = 'bar' // ok
    
    let onlyNumbers: KeysOfType<Foo, number>;
    onlyNumbers = 'baz' // ok
    onlyNumbers = 'bar' // error 
    
    0 讨论(0)
提交回复
热议问题