type ItemX = { type: 'X', value: 'X1' | 'X2' | 'X3' };
type ItemY = { type: 'Y', value: 'Y1' | 'Y2' };
type Item = ItemX | ItemY;
function processItem(item: Item) {
// ...
}
function multipleItems<I extends Item, T extends I['type'], V extends I['value']>(type:T, value: V) {
// ... type and value should be
}
// Examples
processItem({ type: 'X', value: 'X1' });
processItem({ type: 'X', value: 'Y1' }); // type error
multipleItems('X', 'X1');
multipleItems('X', 'Y1'); // no type error
Is there any way to make this last example cause a type error, just like in the second example, but only using two parameters (type
and value
)?
I tried this solution, but it would require me to add a third parameter like item: I
to the multipleItems
function. Anyway, in that case, the first fn processItem
would be simpler.