Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

key of type -> boolean is not assignable to type never

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;
      }
    }
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!
}

Online Typescript editor

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading