如何为打字稿配置中的变量启用具有typeof标志的联合类型
在第一行中删除类型定义很好,但是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
}
}
减速器中的类型定义应能正常工作,但会显示出超标
答案 0 :(得分:0)
使用类代替接口并使用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
}
}
但是,如果要保留接口,则应将代码更改为此:
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
}
}
问题在于TYPEA
和TYPEB
被推断为number
,而不是数字文字(1
,2
)。