【发布时间】:2019-06-28 11:04:15
【问题描述】:
我一直在尝试创建一个由 T 类型的键组成的类型,其值为字符串。在伪代码中,它将是 keyof T where T[P] is a string。
我能想到的唯一方法是分两步:
// a mapped type that filters out properties that aren't strings via a conditional type
type StringValueKeys<T> = { [P in keyof T]: T[P] extends string ? T[P] : never };
// all keys of the above type
type Key<T> = keyof StringValueKeys<T>;
但是 TS 编译器说 Key<T> 简单地等于 keyof T,尽管我已经通过使用条件类型将它们设置为 never 过滤掉了值不是字符串的键。
所以它仍然允许这样做,例如:
interface Thing {
id: string;
price: number;
other: { stuff: boolean };
}
const key: Key<Thing> = 'other';
当key 的唯一允许值确实应该是"id",而不是"id" | "price" | "other",因为其他两个键的值不是字符串。
【问题讨论】:
-
可能复制Define generic typescript sort function of a certain type,或者至少我的答案是一样的
标签: typescript generics typescript-generics mapped-types