我有一个键为type
和playground
的对象。所以我希望payload
类型基于type
类型
enum Type {
TYPE_A,
TYPE_B,
UNKNOWN,
}
interface PayloadA {
name: string;
}
interface PayloadB {
value: number;
}
type Entity = { type: Type.TYPE_A; payload: PayloadA } | { type: Type.TYPE_B; payload: PayloadB } | { type: Type.UNKNOWN; payload: {} };
function getType(typename: string): Type {
switch (typename) {
case 'a':
return Type.TYPE_A;
case 'b':
return Type.TYPE_B;
default:
return Type.UNKNOWN;
}
}
function getPayload(typename: string): Entity['payload'] {
switch (typename) {
case 'a':
return { name: '' };
case 'b':
return { value: 0 };
default:
return {};
}
}
const typename = 'a';
const entity: Entity = {
type: getType(typename),
payload: getPayload(typename),
};
在这里抛出错误
const entity: Entity = {
Type 'Type' is not assignable to type 'Type.UNKNOWN'
你能帮我吗?我不知道如何编写正确的类型