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

Typescript index signature with an exception not working for array

For the following code

❌ let b:({[key:string]:string} & {test:number})[] = [{yes:"yes", test:3}]; 

Why does the definition b show an error?

Type '{ yes: string; test: number; }' is not assignable to type '{ [key: string]: string; } & { test: number; }'.
  Type '{ yes: string; test: number; }' is not assignable to type '{ [key: string]: string; }'.
    Property 'test' is incompatible with index signature.
      Type 'number' is not assignable to type 'string'.ts(2322)

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 :

Replacing & with | fixes the issue for me

let a:{[key:string]:string} | {test:number} = {yes:"yes", test:3}; 
let b:({[key:string]:string} | {test:number})[] = [{yes:"yes", test:3}]; 

& takes the common part of the two types, but there is no common part of {[key:string]:string} and {test:number}

TS playground

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