Home > Enterprise >  I have two interfaces and I would like to merge only the ids of the interfaces
I have two interfaces and I would like to merge only the ids of the interfaces

Time:09-23

I am trying to update a property that nested Inside an array of objects and that object has another array of objects. In order to update the property I need the Ids (or indexes) of both arrays to update the property. So I created the interfaces:

export interface ILaser {
    id: 'L1' | 'L2' | 'L3' | 'L4' | 'L5' | 'L6';
    name:
        | 'Laser #1'
        | 'Laser #2'
        | 'Laser #3'
        | 'Laser #4'
        | 'Laser #5'
        | 'Laser #6';
    switchMode: Number;
    pulseWidth: Number;
    power: Boolean;
}

export interface IOpticalHeadUnit {
    id: 'OHU1' | 'OHU2' | 'OHU3';
    name:
        | 'Optical Head Unit #1'
        | 'Optical Head Unit #2'
        | 'Optical Head Unit #3';
    lasers: Array<ILaser>;
}

I want to update the power of the laser inside the optical head unit. I created a function to get both ids and update the power, but I need now to create a third interface to correct the ts error, but I only want the ids of both interfaces so if i add another laser or Optical head unit I won't have to update in both locations.

Something like this:

interface ILaserIdAndIOpticalUnitId{
laserId: ILaser.id;
opticalHeadUnitId: IOpticalHeadUnit.id;

Is it possible to accomplish in typescript?

CodePudding user response:

You need to use square bracket notation, just like in plain js:

export interface ILaser {
    id: 'L1' | 'L2' | 'L3' | 'L4' | 'L5' | 'L6';
    name:
    | 'Laser #1'
    | 'Laser #2'
    | 'Laser #3'
    | 'Laser #4'
    | 'Laser #5'
    | 'Laser #6';
    switchMode: Number;
    pulseWidth: Number;
    power: Boolean;
}

export interface IOpticalHeadUnit {
    id: 'OHU1' | 'OHU2' | 'OHU3';
    name:
    | 'Optical Head Unit #1'
    | 'Optical Head Unit #2'
    | 'Optical Head Unit #3';
    lasers: Array<ILaser>;
}

interface ILaserIdAndIOpticalUnitId {
    laserId: ILaser['id'];
    opticalHeadUnitId: IOpticalHeadUnit['id']
}

Playground

CodePudding user response:

A simple fix using indexed access types:

interface ILaserIdAndIOpticalUnitId {
  laserId: ILaser['id'];
  opticalHeadUnitId: IOpticalHeadUnit['id'];
}

const foo: ILaserIdAndIOpticalUnitId = {
  laserId: 'L1',
  opticalHeadUnitId: 'OHU1'
};

Out of curiosity, an intersection type:

type ID = ILaser['id'] | IOpticalHeadUnit['id'];
const foo: ID = 'L1';
const bar: ID = 'OHU1';
  • Related