基于其他类型的类型

时间:2020-10-29 08:57:16

标签: typescript

我有一个键为typeplayground的对象。所以我希望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'

你能帮我吗?我不知道如何编写正确的类型

TypeScript code playground

0 个答案:

没有答案