我有一个通用实体类型,该通用用于基于一组字符串文字定义字段类型:
type EntityTypes = 'foo' | 'bar' | 'baz';
type EntityMappings = {
foo: string;
bar: number;
baz: Array<string>;
}
type GenericEntity<T extends EntityTypes> = {
type: T;
fieldProperty: EntityMappings[T];
}
Run Code Online (Sandbox Code Playgroud)
我想做的是要求 GenericEntity 的所有实例都有一个type字段(字符串文字),然后定义 fieldProperty 的类型,例如:
const instance: GenericEntity<'foo'> = {
type: 'foo',
fieldProperty: 'hello',
};
const otherInstance: GenericEntity<'baz'> = {
type: 'baz',
fieldProperty: ['a', 'b', 'c'],
}
Run Code Online (Sandbox Code Playgroud)
但是,因为T extends EntityTypes允许 EntityType 中多个字符串文字值的联合,所以我能够执行此操作,但我想禁止这样做:
const badInstance: GenericEntity<'foo' | 'baz'> = {
type: 'baz',
fieldProperty: 'blah',
};
Run Code Online (Sandbox Code Playgroud)
之所以能够编译,是因为 …