首页 > 解决方案 > 如何在Typescript中使用定义为多种类型之一的变量来对抗其中一种类型的数组?

问题描述

这是一个显示问题核心的极简示例,希望它有助于理解我的案例

interface Type1 {value1: number};
interface Type2 {value2: string};

let variable: Type1|Type2;

let variableType1List: Type1[];
let variableType2List: Type2[];

let usingType1: boolean = true;
let variableListPosition: number;

if (usingType1) {
    variable = {value1: 5};
} else {
    variable = {value2: "hello world"};
}

if (usingType1) {
    variableListPosition = variableType1List.indexOf(variable);
} else {
    variableListPosition = variableType2List.indexOf(variable);
}

我收到类型为 'Type1 | 的错误参数 Type2 不可分配给“Type1”类型的参数。“Type2”类型中缺少属性“value1”,但在“Type1”类型中是必需的。连续

variableListPosition = variableType1List.indexOf(variable);

我得到类型为 'Type1 | 的错误参数 Type2' 不可分配给'Type2' 类型的参数。“Type1”类型中缺少属性“value2”,但在“Type2”类型中是必需的。连续

variableListPosition = variableType2List.indexOf(variable);

一件事是这可以通过创建具有共享逻辑的父类然后为特定类型定义子类来解决。但是我仍然很好奇这样的事情是否可行,因为有时我希望允许将多种类型的变量传递到我的函数中,然后以稍微不同的方式使用它们,以使我的类更易于其他程序员使用。

谢谢您的答复!

标签: javascriptreactjstypescript

解决方案


我不认为这是你的问题。在您的示例中,每次输入都有意义。出了问题的是 TS 的股票类型.indexOf()接受数组元素类型的参数,这对我来说显然是一个过度杀伤力的约束。

这就像isString()只需要string作为参数,我的意思是,如果我知道它是 astring那么我根本不需要调用它。同样.indexOf经常被用作一种测试方法,并且可以将它用于任何事情。

我的建议,只是as any用来绕过它。

variableListPosition = variableType2List.indexOf(variable as any);

或者,您也可以通过声明合并来修改 TS stock lib 的类型。值得庆幸indexOf的是,它是一个函数,您可以毫无问题地添加重载签名。

declare global {
    interface Array<T> {
        indexOf(searchElement: any, fromIndex?: number): number
    }
}

推荐阅读