I'm trying to access a variable with type indexing in Angular 13 and am getting a TS7053 error. This stackblitz shows exactly what I'm doing however it works perfectly fine in there with no error.
export class AppComponent {
name = 'Angular ' VERSION.major;
Prop01 : boolean = false;
Prop02 : boolean = false;
Prop03 : boolean = false;
private setProp(prop: string, value: boolean): void {
this[prop] = value; // this works in the Stackblitz but not in my project
}
}
The only difference is I'm using V13 while stackblitz still uses V12. I looked at my VS Code extensions and saw Ts Lint
was deprecated in favor of Es Lint
so I disabled it and rebooted VS Code but this[prop]
still throws an error that says
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MyComponent'. No index signature with a parameter of type 'string' was found on type 'MyComponent'.
I've done this in older versions of Angular so I don't understand what's making it not work all of a sudden, anyone know why this is?
CodePudding user response:
I would suggest creating an enum
with those variable names:
export enum MyEnums {
Prop01: 'Prop01',
Prop02: 'Prop02',
Prop03: 'Prop03'
}
Component:
import {myEnum} from './myEnums.ts'
export class AppComponent {
name = 'Angular ' VERSION.major;
Prop01 : boolean = false;
Prop02 : boolean = false;
Prop03 : boolean = false;
private setProp(prop: string, value: boolean): void {
this[prop as MyEnum] = value;
console.log(this[prop as myEnum]); // true or false, whatever your send
}
}
Angular v12 was the first version it included strict mode
enable (which is really good) by default, so it's pretty much being strict asking you to create a signature for accessing that parameter.
You could do that in older versions since strict mode was not enable there unless you set it "on" manually
CodePudding user response:
As you are using 3 separate variables instead of an object (for objects there are plenty of questions and answers to, e.g: Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; })
In your case with your variables I would use a type
with your variable names declared and then you can call as
for your type. So something like:
export type PropType = 'Prop01' | 'Prop02' | 'Prop03';
and then your function:
private setProp(prop: string, value: boolean): void {
this[prop as PropType] = value;
}