简体   繁体   English

TypeScript keyof 返回特定类型

[英]TypeScript keyof returning specific type

If I have the following type如果我有以下类型

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

can I use typeof to type a parameter such that it only takes keys of Foo that return string ( 'bar' or 'qux' )?我可以使用typeof键入一个参数,以便它只需要返回string'bar''qux' )的Foo键?

You can use conditional types in Tyepscript 2.8 :您可以在 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM