我在Typescript的文档中读到,我可以创建一个Map类型,可以用来将可能的键约束为特定类型的键:
type OptionsFlags<Type> = {
[K in keyof Type]: boolean;
};
字符串
但是如果我想让一个泛型类型作为一个只接受字符串的值:
type Key<K extends string> {
key: K
}
型
那么这个就不起作用:
type OptionsFlags<Type> = {
[K in keyof Type]: Key<K>;
};
型
因为
Type 'K' does not satisfy the constraint 'string'.
Type 'keyof Type' is not assignable to type 'string'.
Type 'string | number | symbol' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'
型
似乎我必须约束Type
中的键,但我如何做到这一点呢?
1条答案
按热度按时间35g0bw711#
你想要这样的东西:
字符串
示例用法(成功):
型
示例用法(失败):
型