我有这种类型(来自第三方库):
type StackActionType = {
type: 'REPLACE';
payload: {
name: string;
key?: string | undefined;
params?: object;
};
source?: string;
target?: string;
} | {
type: 'PUSH';
payload: {
name: string;
params?: object;
};
source?: string;
target?: string;
} | {
type: 'POP';
payload: {
count: number;
};
source?: string;
target?: string;
} | {
type: 'POP_TO_TOP';
source?: string;
target?: string;
};
我想推断剩余的联合类型。 我可以通过字段键/名称来实现这一点。例如:
const action: StackActionType = ...;
if("payload" in action) {
// action is infered with union types of: 'REPLACE', 'PUSH', 'POP' (contains "payload" field) and 'POP_TO_TOP' is omited
}
但是有一种方法可以使用字段值而不是字段名称来实现这一点,例如:
if(["PUSH", "REPLACE"].includes(action.type)) {
// action should only infer union of 'REPLACE' & 'PUSH'. But this is not working...
}
有什么想法(不复制/改变原始类型)吗?
编辑:
这是使用类型保护 & if 的尝试: Typscript sandbox
最佳答案
我相信如果您使用以下方法,您的解决方案将会起作用:
if (action.type == 'PUSH' || action.type == 'REPLACE') {}
当您使用 [].includes
时,Typescript 无法静态分析类型可能性,因为数组在技术上可以包含动态(运行时)值。
关于typescript - 如何根据字段值省略联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72199408/