javascript - 如何在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);
一件事是这可以通过创建具有共享逻辑的父类然后为特定类型定义子类来解决。但是我仍然很好奇这样的事情是否可行,因为有时我希望允许将多种类型的变量传递到我的函数中,然后以稍微不同的方式使用它们,以使我的类更易于其他程序员使用。
谢谢您的答复!
解决方案
我不认为这是你的问题。在您的示例中,每次输入都有意义。出了问题的是 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
}
}
推荐阅读
- javascript - 带有自定义寻呼机的 bx 滑块在悬停时在幻灯片之间移动时出现问题
- android - 模拟器 AVD 无法将显示缩放到 4k 显示器
- android - 如何使用 React Native 去除 android 上状态栏上的黑色覆盖
- docker - 运行 docker-compose 后 Drupal 8 文件夹为空
- python - 如何找出上次按下哪个按钮 python tkinter
- python - 无法在 python 脚本中导入 google.cloud 模块
- python-3.x - 如何让 ZipFile 仅压缩指定目录 - Python 3
- azure - Azure iothub 设备孪生使用 golang 引发 InternalServerError
- bigtable - BigTable:2 次写入相同的密钥,但有 3 个版本
- assembly - 使用 file_name equ "a.txt" 后打开时出现 EFAULT 错误?