Home > other >  How should I access attributes of union types in typscript?
How should I access attributes of union types in typscript?

Time:02-14

What is the correct way to access attributes of a union type that is not present on all of the types? I seem to always get a typescript "property ... does not exist on type..." error, even if I do a check to make sure the attribute exists (see example below)

interface Car {
  wheels: 4,
  spareWheels: 1,
}

interface Bicycle {
  wheels: 2,
}

type Vehicle = Car | Bicycle


getWheelCount(vehicle: Vehicle): number => {
   return vehicle.spareWheels ? vehicle.spareWheels   vehicle.wheels : vehicle.wheels
}

The documentation (https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types ) has a solution to use 'typeof', but that doesn't work for custom types.

CodePudding user response:

You can use in operator like this:

interface Car {
  wheels: 4;
  spareWheels: 1;
}

interface Bicycle {
  wheels: 2;
}

type Vehicle = Car | Bicycle;

const getWheelCount = (vehicle: Vehicle): number => {
  return "spareWheels" in vehicle // using `in` operator
    ? vehicle.spareWheels   vehicle.wheels
    : vehicle.wheels;
};

CodePudding user response:

You can use type-predicates.

interface Car {
  wheels: 4;
  spareWheels: 1;
}

interface Bicycle {
  wheels: 2;
}

type Vehicle = Car | Bicycle;

const getWheelCount = (vehicle: Vehicle): number => {
  return isVehiculeCar(vehicle) ? vehicle.spareWheels   vehicle.wheels : vehicle.wheels;
};

const isVehiculeCar = (subject: Vehicle): subject is Car => {
  return (subject as Car).spareWheels !== undefined;
};

This way typescript you know when you are dealing with a Car or a Bicycle.

  • Related