Home > database >  Isolating typescript variable declarations with long interfaces into own file
Isolating typescript variable declarations with long interfaces into own file

Time:01-13

I'm wondering whats the best practice of declaring default values on variables, where the interface consists of many properties.

For example theres a following interface:

interface House {
  color: string,
  windows: number,
  width: number,
  height: number,
  depth: number,
  doors: number,
  address: string,
  postCode: string,
  city: string,
  ...
}

Now everywhere I want to use this interface, I need to provide a value for each of the properties. Even if I want to update just a couple properties at a time, I have to declare all of them, which pollutes the file unnecessarily. Now I know I can make the fields optional, but this is not what im looking for.

Is there a practice for separating the declaration of such variable into some different file?

CodePudding user response:

if you are trying to declare interface in two different ways, this is not possible, however you can use Pick in TypeScript as mentioned in Chris Heald comment above.

this allow you to use a part of the interface as another interface. for example if you need only width and height propreties, you can PICK them like this :

let houseSize : Pick<House , 'width' | 'height'> = { height: 13, width: 14 };

CodePudding user response:

Your House type can probably benefit from compositional modelling.

Looking over the members of the type, it seems like the entire type is composed of groups of logically related members. For example:

TS Playground

type Address = {
  address: string;
  city: string;
  postCode: string;
};

type Dimensions = {
  depth: number;
  height: number;
  width: number;
};

type FeatureCounts = {
  doors: number;
  windows: number;
};

type StyleProps = {
  color: string;
};

The House type represents a combination of all of those groups of attributes:

type House = Address & Dimensions & FeatureCounts & StyleProps;

By breaking apart the groups of related properties, it then becomes easier to work with each of them as needed — for example, updating a house's address:

function updateHouseAddress (house: House, address: Address): void {
  // implementation...
}

And, as @AlexWayne mentioned, TypeScript offers quite a few built-in utility types (e.g. Partial<Type>, Pick<Type, Keys>, Omit<Type, Keys>, etc.) for deriving other types from existing type information.

See also:

  • Related