skip to Main Content

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)

2

Answers


  1. 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

    Login or Signup to reply.
  2. TypeScript becomes more strict when using index signatures with intersection types in arrays.

    When dealing with complex types, TypeScript tries to ensure that the types are as accurate and safe as possible. This strictness can sometimes lead to scenarios where certain type combinations seem to work in isolation but not in more complex structures, such as arrays or objects. And this is your use case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search