我有一个泛型实体类型,该泛型用于根据一组字符串文字定义字段类型:
type EntityTypes = 'foo' | 'bar' | 'baz';
type EntityMappings = {
foo: string;
bar: number;
baz: Array<string>;
}
type GenericEntity<T extends EntityTypes> = {
type: T;
fieldProperty: EntityMappings[T];
}
我想要做的是要求 GenericEntity 的所有实例都有一个 type
然后定义 fieldProperty 类型的字段(字符串文字),例如:
const instance: GenericEntity<'foo'> = {
type: 'foo',
fieldProperty: 'hello',
};
const otherInstance: GenericEntity<'baz'> = {
type: 'baz',
fieldProperty: ['a', 'b', 'c'],
}
但是,因为T extends EntityTypes
允许在 EntityTypes 中合并多个字符串文字值,我能够做到这一点,但我想禁止这样做:
const badInstance: GenericEntity<'foo' | 'baz'> = {
type: 'baz',
fieldProperty: 'blah',
};
编译是因为现在 type
类型为 'foo' | 'baz'
fieldProperty 的类型是 string | Array<string>
, 但是这两个字段不再像我预期的那样对应。
有没有办法进一步限制 GenericEntity 上的泛型声明,只允许一个唯一的字符串文字值?除此之外,是否有其他方法可以坚持 GenericEntity 的任何实例都具有 type
场和一个fieldProperty
对应的字段?
最佳答案
目前没有直接的方法来限制 generic union 的单个成员的类型参数.在 microsoft/TypeScript#27808 有一个开放的功能请求支持类似 T extends <em>oneof</em> EntityTyes
的东西, 但尚未实现。如果你想看到它发生,你可以访问那个问题并给它一个