我在Angular 2应用程序中收到此编译错误:
TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
Run Code Online (Sandbox Code Playgroud)
导致它的代码是:
getApplicationCount(state:string) {
return this.applicationsByState[state] ? this.applicationsByState[state].length : 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,这不会导致此错误:
getApplicationCount(state:string) {
return this.applicationsByState[<any>state] ? this.applicationsByState[<any>state].length : 0;
}
Run Code Online (Sandbox Code Playgroud)
这对我没有任何意义.我想在第一次定义属性时解决它.目前我正在写:
private applicationsByState: Array<any> = [];
Run Code Online (Sandbox Code Playgroud)
但有人提到问题是试图在数组中使用字符串类型作为索引,我应该使用映射.但我不知道该怎么做.
有你的帮助!
Trying out TypeScript for a React project and I'm stuck on this error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'.
No index signature with a parameter of type 'string' was found on type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'
Run Code Online (Sandbox Code Playgroud)
Which appears when I try to filter the array in my component
.filter(({ name }) => plotOptions[name]); …Run Code Online (Sandbox Code Playgroud) 在编写纯 Javascript 时,我经常构建带有“config”属性的类,其键有一些默认值,例如:
class MyClass{
config = {
someProp:true,
otherProp:5
}
constructor(config){
for(let prop in config){
this.config[prop] = config[prop]
}
}
}
Run Code Online (Sandbox Code Playgroud)
这非常方便,因为我可以循环遍历传递的对象并覆盖默认值(如果提供了值)
在打字稿中,我尝试了这样的事情:
class MyClass{
config = {
someProp:true,
otherProp:5
}
constructor(config?: { someProp?: boolean,otherProp?:number }) {
if (config) {
for (let prop in config) {
this.config[prop] = config[prop]
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“{ someProp: boolean;” otherProp:数字;}'。在类型“{someProp: boolean;”上找不到带有“string”类型参数的索引签名 otherProp:数字;}'。
我或多或少理解这个错误的含义,但我想我这里的整个方法非常“类似 JS”,应该改变。
在 Typescript 中执行此操作的传统、简单方法是什么?其想法是快速将提供的属性与默认属性合并,而无需重复各种检查。
当 Javascript 更新一个对象时,就像下面这样。
const data = {
a: 1,
b: 3,
c: 4
}
const update = (summary) => {
data[summary] += 1;
console.log(data);
}
update('a');
Run Code Online (Sandbox Code Playgroud)
我用 Typescript 尝试了同样的事情,但它不起作用,因为我知道我做错了什么,有人可以指出错误以及如何解决问题。
interface Summary {
a: number,
b: number,
c: number
}
const data: Summary = {
a: 1,
b: 3,
c: 4
}
const updateData = (summaryType: string) => {
data[summaryType] += 1 // Error
}
Run Code Online (Sandbox Code Playgroud)
错误是 -> 元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“Summary”。在“Summary”类型上找不到带有“string”类型参数的索引签名。(7053)