My type declarations are as follows:
types.ts:
type ItemKind = 'A' | 'B';
type ValidItem<TItemKind extends ItemKind = ItemKind> = {
readonly type: TItemKind;
readonly id: number;
};
type EmptyItem<TItemKind extends ItemKind = ItemKind> = {
readonly type: `empty-${TItemKind}`;
};
export type Item = ValidItem | EmptyItem;
Now, I am faced with the task of finding an item element by its id
property within an array of Items
and accessing its value.
Although I have managed to implement a predicate function that successfully locates the desired element, I am struggling with how to utilize and cast the object once it has been found.
index.ts:
import { type Item } from './types';
const items: Items[] = [
{type: 'A', id: 42},
{type: 'empty-A'},
{type: 'empty-B'}
];
console.debug('Items', items);
const targetId = 42;
const item = items.find((item) =>
item.type === 'A' && item.id === targetId // This works
);
if (item) {
console.debug('Item', item);
// How can I typecast and access the id property??
// For example:
// console.debug('Id', item.id); // But this results in an error
}
You can execute the code like this:
$ npx ts-node index.ts
Items [ { type: 'A', id: 42 }, { type: 'empty-A' }, { type: 'empty-B' } ]
Item { type: 'A', id: 42 }
I would greatly appreciate any assistance. Unfortunately, I am unable to modify the existing type structure or declarations.