TypeScript 接口(interface)数组类型错误 TS2411

标签 typescript

我很难理解这一点:

There are two types of supported index types: string and number. It is possible to support both types of index, with the restriction that the type returned from the numeric index must be a subtype of the type returned from the string index.

While index signatures are a powerful way to describe the array and 'dictionary' pattern, they also enforce that all properties match their return type. In this example, the property does not match the more general index, and the type-checker gives an error:

interface Dictionary {
    [index: string]: string;
    length: number;    // error, the type of 'length' is not a subtype of the indexer
}

来源:TypeScript Handbook's interface

我已经尝试了 4 个案例,但仍然无法理解发生了什么。谁能解释为什么只有 [index: string]: string; 会有错误 TS2411? enter image description here

另一种情况:

another case

最佳答案

如果您有 [index: string]: string; 所有属性都必须是 string。因此:

interface Dictionary {
    [index: string]: string;
    length: number;    // error, length is not a string.
}

关于TypeScript 接口(interface)数组类型错误 TS2411,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33818178/

相关文章:

javascript - tsconfig.json 和 typings.json 之间的关系?

javascript - 为什么 TypeScript 不对 Promise 强制执行 async/await?

javascript - typescript : react 事件类型

javascript - 如何在 Angular2 组件之间共享数据

javascript - 从另一个更新一个 React 的组件状态

javascript - 对使用 angular 和 typescript 链接 $q promises 感到困惑

reactjs - 在 React-bootstrap 的 OverlayTrigger 放置属性上使用字符串变量时出现问题

generics - 在 TypeScript 中转换通用接口(interface)类型

javascript - 为什么 "reject"在此代码中实际上并未拒绝?

angular - "no-unused-variable": true is not working in VSCode