I'm not able to get the following to typecheck:
type Apple = {
variety: {type: 'fuji'} | {type: 'gala'}
}
type FujiApple = {
[P in keyof Apple]: P extends 'variety'
? Extract<Apple['variety'], {type: 'fuji'}>
: Apple[P]
}
function fujiFn(fugi: FujiApple) {}
function appleFn(apple: Apple) {
if (apple.variety.type === 'fuji') {
// FAILS: Argument of type 'Apple' is not assignable to parameter of type
// 'FujiApple'
fujiFn(apple)
}
}
Is there a way to type this to get the narrowing to work as intended? This happens only when the discriminator is not at the top level.
Solution I don't Like:
The following actually works, but it's... ugly and I would rather not do this.
fujiFn({...apple, variety:apple.variety})