Home > Enterprise >  How do you define a typescript record where some of the keys have types and the others are freeform?
How do you define a typescript record where some of the keys have types and the others are freeform?

Time:10-09

I want to have the types for some of the keys in the record to be strict, and the remainder to be freeform.

type Make "Volvo" | "Polestar" | "Saab";
interface Car {
    make: Make;
    horsePower: number;
    allWheelDrive: boolean;
    ...
}

and I want it accept

{
    make: "Saab",
    horsePower: 232,
    allWheelDrive: true,
    colour: "blue",
    trim: "leather
}

but not

{
   make: "Daimler",
   horsePower: 199,
   allWheelDrive: false,
   colour: "blue",
   trim: "leather
}

How do I write the Car interface to be able to do this with typescript?

CodePudding user response:

I think that enums would be the best for your purpose

enum Make {
    Volvo="Volvo",
    Polester="Polseter",
    Saab="Saab" 
}

interface Car {
    make: Make;
    horsePower: number;
    allWheelDrive: boolean;
}

CodePudding user response:

I think you want to have "specialized" variants.

Each one of the variants has specific fields and types, and at the end there is a more "generic" one:

interface FooCar {
  make: 'foo';
  something: false;
  extraField: string;
}
interface BarCar {
  make: 'bar';
  something: true;
}
interface BazCar {
  make: 'baz';
  something: boolean;
  explosionProbability: number;
}

type Car =
  | FooCar
  | BarCar
  | BazCar
  | {
      make: string;
      something: boolean;
    };

  • Related