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
Replacing
&
with|
fixes the issue for me&
takes the common part of the two types, but there is no common part of{[key:string]:string}
and{test:number}
TS playground
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.