I might be asking too much of Typescript, but I was wondering if something like this is possible:
interface ObjectType {
type: 'this' | 'that';
}
interface SomeObject {
objType: ObjectType
}
interface ThisObject extends SomeObject {
objType: { type: 'this' }
thisProp: 'anything'
}
interface ThatObject extends SomeObject {
objType: { type: 'that' };
thatProp: 'something'
}
function getProp(obj: ThisObject | ThatObject) {
switch (obj.objType.type) {
case 'this':
return {
type: obj.objType.type,
prop: obj.thisProp
};
case 'that':
return {
type: obj.objType.type,
prop: obj.thatProp
};
}
}
Typescript is able to correctly narrow obj.objType.type
, but the value I'm trying to assign to prop
in the returned object doesn't typecheck. Errors are the same for both (obviously with different property names):
TS2339: Property 'thatProp' does not exist on type 'ThisObject | ThatObject'. Property 'thatProp' does not exist on type 'ThisObject'.
Is something like this possible? I also tried something like this:
interface SomeObject {
objType: ObjectType;
thisProp: SomeObject['objType'] extends 'this' ? 'anything' : never;
thatProp: SomeObject['objType'] extends 'that' ? 'something' : never;
}
which results in both props being never
, as well as something like this:
type PickObject<T> = T extends 'this' ? ThisObject : ThatObject;
function getProp<T extends 'this' | 'that'>(obj: PickObject<T>) {
switch (obj.objType.type) {
case 'this':
return {
type: obj.objType.type,
prop: obj.thisProp
};
case 'that':
return {
type: obj.objType.type,
prop: obj.thatProp
};
}
}
which results in the same error:
TS2339: Property 'thisProp' does not exist on type 'PickObject '.
interface ThisObject extends SomeObject { objType: { type: 'this' }; thisProp: 'anything' }
andinterface ThatObject extends SomeObject { objType: { type: 'that' }; thatProp: 'something' }
. That wouldn't make nested discriminated unions magically work, unfortunately, but at least your types would correspond to what you're actually doing.