Home > Software design >  Typescript type conversion using destructuring rest on deep object
Typescript type conversion using destructuring rest on deep object

Time:10-19

// inital types
 interface Source {
  id: string;
  version: number; // discard
  masterVariant: MasterVariant;
}

interface MasterVariant {
  id: number; // discard
  sku?: string;
}


// desired "lighter" types
 interface Target {
  id: string;
  masterVariant: MasterVariantLight;
}

interface MasterVariantLight {
  sku?: string;
}

to remove version property we can use the following

export class Convert {
    public static toTarget(source: Source): Target {
      const { version, ...result } = source;  
      return result;
    }
  }

can you see a way to discard masterVariant.id using above transformation?

CodePudding user response:

export class Convert {
  public static toTarget(source: Source): Target {
    const { version, masterVariant: { id, ...rest }, ...result } = source;
    return { id: result.id, masterVariant: { ...rest } };
  }
}

Playground

CodePudding user response:

While pure destructuring is possible here, I think it'd be clearer to use one more line to construct the required masterVariant format.

Having a class that never gets instantiated doesn't make much sense either - a plain function would be more suitable for the task (which is fine, unlike in Java).

const toTarget = (source: Source) => {
    const { masterVariant, ...origSource } = source;
    const newMasterVariant = { sku: masterVariant.sku };
    return { ...origSource, masterVariant: newMasterVariant };
};
  • Related