首页 > 解决方案 > 传递索引类型时,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吗?

标签: typescript

解决方案


似乎有人可能在某个时候考虑过这种行为:“当目标是弱类型并且源具有至少一个属性,调用签名或构造签名时,会发生弱类型检查”(此评论)。但这条规则对我来说仍然没有意义。我继续提交了一个新问题。如果向 中添加属性(甚至是可选属性)IndexedInterface,则会按预期报告错误。


推荐阅读