I have the following variations:
type First = { kind: 'First', name: string }
type Second = { kind: 'Second', title: string }
type Combo = First | Second;
I am attempting to locate the element of type First
in a Combo[]
, as shown below:
const elements: Combo[] = [
{ kind: 'First', name: 'element 1' },
{ kind: 'Second', title: 'element 2' },
]
const foundFirst: First | undefined = elements.find(e => e.kind === 'First');
However, this triggers the error:
Type 'First | Second | undefined' is not assignable to type 'First | undefined'.
Property 'name' is missing in type 'Second' but required in type 'First'.
The predicate function for Array.prototype.find
correctly identifies the appropriate type, and I can access the properties of First
without any issues:
https://i.sstatic.net/xuS6V.png
It seems to be the return type that needs refinement.
The only solution I have found so far is using a for loop, but it seems cumbersome and unnecessary.
let foundElement: First | undefined;
for (let i = 0; i < elements.length; i++) {
const value = elements[i];
if (value.kind === 'First') {
foundElement = value;
break;
}
}