typescript - Typescript - 同一界面中相同类型的固定属性和可选属性
问题描述
正如标题所说,有一个接口,其中包括一个固定属性和可选属性,两者都是 type string
。
export interface Test{
[index: string]: {
'list': string[]; // <<< throws TS2411 error
[index: string]: number;
}
}
这会引发 TS 错误TS2411: Property 'list' of type 'string[]' is not assignable to string index type 'number'.
我该如何解决这个问题?
我知道list
元素将存在于每个根索引对象中,所有其他属性(如果存在)都是数字类型。
如果我将界面更改为:
export interface Test{
[index: string]: {
'list': string[];
[index: string]?: number; // <<< throws TS7008 error
}
}
然后我得到TS7008: Member 'number' implicitly has an 'any' type.
解决方案
这是因为您正在设置[index: string]: number;
部分 - 允许您将任何字符串设置为数字,这也涵盖了“列表”的字符串,因此存在冲突。如果您需要“列表”值以及未知数量的其他值,我建议您这样做:
export interface Test {
[index: string]: {
list: string[];
items: {
[index: string]: number;
}
}
}
推荐阅读
- c# - 我用于更改存储在数据库中的值的新值输入没有改变
- javascript - 使用 javascript 在 PHP 中交换复选框
- python - 将字典保存为 Python 脚本
- node.js - 如何使用护照 js 在 req.body 中添加用户?
- interface - 显式选择接口实现的类似 Haskell TypeApplication 的方式
- ansible - Ansible 内置 Lineinfile 到 ~/.bashrc
- python - 如何在python中提取频率分布表(直方图)
- ffmpeg - pyav / libav / ffmpeg 当来自实时源的帧处理速度不够快时会发生什么
- c++ - 继承的静态工厂方法返回子类类型
- github-for-windows - Windows 上的 github 运行程序在 PowerShell 上找不到可执行文件