javascript - 如何在 TypeScript 界面中强制键类型?

标签 javascript typescript

我想创建一个对象接口(interface),强制使用字符串作为键,但 TypeScript 编译器传递代码,即使它有数字类型作为键。为什么?

例如,

interface PriceI {
    [key:string]:number;
}

var coursePrice: PriceI = {};
coursePrice["Orange"] = 100;
coursePrice["Apple"] = 200;
coursePrice[3]=200;    // It should be compile error, but it pass
coursePrice[true]=300; // It's compile error

最佳答案

参见the handbook :

There are two types of supported index signatures: string and number. It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a number, JavaScript will actually convert that to a string before indexing into an object. That means that indexing with 100 (a number) is the same thing as indexing with "100" (a string), so the two need to be consistent.

在您的示例中,TypeScript 认为 coursePrice[3] = 200; 相当于 coursePrice["3"] = 200;

关于javascript - 如何在 TypeScript 界面中强制键类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37069430/

相关文章:

Angular 6 应用程序找不到命名空间 'google'

javascript - Angular 属性在类型 'Window' 上不存在

javascript - Rollup + Typescript + ESLint 错误警告

javascript - 如何销毁片段(或 View )?

javascript - Bitly API - 如何使用纯 javascript 缩短链接,没有可用的库(甚至没有 jquery)

javascript - 具有嵌套对象数组的对象数组

javascript - 如何在 perl CGI 中获取访问者浏览器窗口大小

javascript - 获取当前元素(keyup)并将其作为参数传递给另一个函数

cordova - 如何在 Angular 2 移动应用程序中使用 Cordova 插件

Angular 库 ng-packagr 不会用相对路径替换 tsconfig 路径