typescript - 如何根据字段值省略联合类型

标签 typescript types

我有这种类型(来自第三方库):

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/

相关文章:

javascript - 将列表项数据从一页传输到另一页

javascript - ts-jest 无法对导入的 ES6 模块运行测试

c# - 条件运算符不能隐式转换?

go - 如何在 Go 中将字节数组转换为字符串

angular - 错误类型错误 : Cannot assign to read only property 'stopImmediatePropagation' of object '[object Object]'

typescript - 如何使用通用组件与 typescript react native

java - 毫无意义的基本 Scala 错误

sql - MySQL:一位的最小数据类型

c++ - typeid(equalizing) 中类型定义及其含义的区别

typescript - 在 export = environment 中导出类型