Skip to content Skip to sidebar Skip to footer

Typescript - Conditional Property Base On Another Property With Union Type Gives An Error

I prepared an union type like below: export type UnionType = | { id: 1; obj: { a: string; b: string; }; } | { id: 2; obj: {

Solution 1:

The problem (at least based on the error) is that if you have a discriminated union, you must perform checks to see in which of the cases you are. You can do this either using a series of if statements, or a switch on the discriminant field:

declareleto: UnionType;

o.obj.b// errorswitch(o.id) {
  case1: o.obj.b; break// ok herecase2: o.obj.b; break// not ok on this branchdefault: assertNever(o); // Optional, ensure no casses are missed, o shoudl be never
}

functionassertNever(o: never) {
  thrownewError("Not supported")
}

Playground Link

Solution 2:

I ended up doing this:

obj["b"]

Post a Comment for "Typescript - Conditional Property Base On Another Property With Union Type Gives An Error"