TypeScript keyof 返回特定类型 [英] TypeScript keyof returning specific type

查看:26
本文介绍了TypeScript keyof 返回特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下类型

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

我可以使用 typeof 来输入一个参数,这样它只需要返回 string ('bar''qux')?

can I use typeof to type a parameter such that it only takes keys of Foo that return string ('bar' or 'qux')?

推荐答案

您可以在 Tyepscript 2.8 中使用条件类型:

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 

这篇关于TypeScript keyof 返回特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆