Issue
I don't understand why I become in my Angular project the TypeScript error Type boolean is not assignable to type never
when I try to set a value to the testObject
.
export interface TestInterface {
text: string;
number: number;
bool1: boolean;
bool2: boolean;
}
export class DamagesComponent implements OnInit {
testObject: TestInterface = {
text: 'test String',
number: 22,
bool1: false,
bool2: true
}
ngOnInit() {
this.toogleVal('bool1')
}
toogleVal(key: keyof TestInterface): void {
if (key in this.testObject) {
if (typeof this.testObject[key] === 'boolean') {
// here the error
this.testObject[key] = true;
}
}
}
}
Solution
When you are accessing the property dynamically, you need to specify in the interface that the key will be a string and the return type will be some data type, the error will go away by modifying the interface to.
export interface TestInterface {
text: string;
number: number;
bool1: boolean;
bool2: boolean;
// this needs to be at the bottom for it to accept the default datatypes of the properties set already!
[key: string]: string | boolean | number;
// [key: string]: any; // or with any data type which is less preferred!
}
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.