接口相似结构的联合类型

Union type for the similar structure of the interfaces

如何在打字稿配置中为变量实现启用 typeof 标志的联合类型

TS playground is there

删除第一行中的类型定义工作正常,但 tslint 为其生成错误。 http://www.typescriptlang.org/docs/handbook/advanced-types.html 中带有(实体)的示例没有帮助。

const TYPE_A: string = 'TYPE_A'; // <- type difinition here breaks line 19
interface Action_A {
    type: typeof TYPE_A;
    payload: {
        entities: [];
    }
}

const TYPE_B = 'TYPE_B';
interface Action_B {
    type: typeof TYPE_B;
    payload: {
        id: number
    }
} 

const shouldBeReducer = (action: Action_A | Action_B) => {
    if (action.type === TYPE_A) {
        return action.payload.entites // <- entities field is not defined
    }
}

reducer 中的类型定义应该可以正常工作,但显示异常

使用 class 代替接口和 instanceof 类型防护。

const TYPEA: number = 1; // type difinition here breaks line 19
class ActionA {
    type: typeof TYPEA;
    payload: {
        entities: [];
    }
}

const TYPEB = 2;
class ActionB {
    type: typeof TYPEB;
    payload: {
        id: number
    }
} 

const reducer = (action: ActionA | ActionB) => {
    if (action instanceof ActionB) {
        action.payload.id // OK
    }
}

Playground

但是如果你想保留接口,你应该将代码更改为:

const TYPEA = 1 as 1; // type difinition here breaks line 19
interface ActionA {
    type: 1;
    payload: {
        entities: [];
    }
}

const TYPEB = 2 as 2;
interface ActionB {
    type: typeof TYPEB;
    payload: {
        id: number
    }
} 

const reducer = (action: ActionA | ActionB) => {
    if (action.type === TYPEB) {
        action.payload.id // OK
    }
}

Playground

问题是 TYPEATYPEB 被推断为 number 而不是数字文字(12)。