typescript - 传递索引类型时,Typescript 的多余属性检查失败
问题描述
我最近通过将索引对象传递给采用具有完全可选属性的接口的方法而被抓住了。我希望这会导致过多的属性检查类型警告,但 Typescript 让它顺利进行。
这是一个最小的情况:
interface SomeInterface {
a?: string;
b?: number;
}
interface IndexedInterface {
[c: string]: SomeInterface;
}
// ...
function fn(t: SomeInterface) {
console.log(typeof t.a); // should always be "string"
}
const something: SomeInterface = {
a: 'string',
b: 1,
};
const indexedThing: IndexedInterface = {
a: something,
};
fn(something); // no error, output: "string", this is fine
fn(indexedThing); // no error, output: "object", this is not fine
有什么方法可以让 Typescript 对这些情况发出警告,或者有人可以解释为什么我可以合法地传递indexedThing
给期望的函数SomeInterface
吗?
解决方案
推荐阅读
- ios - 如何从顶部定位 NavigationBar x 像素
- javascript - 如何在 Bootstrap 的选项卡中添加链接?
- python - 带有类成员的 pybind11 缓冲区协议
- css - 修复重叠的嵌套 Div 元素
- javascript - 逗号分隔的有效手机号码的正则表达式
- reactjs - 在 fetch 方法中加载状态不会更改为 true
- c# - CPU/IO密集型异步任务(mysql数据库连接失败)
- hiveql - 如何在日期分区中获取最近 3 个月
- git - 当您在 git 中推送分支时,是否会推送对本地分支的引用?
- javascript - 如何使用复选框向数组添加/删除项目?