#Is there any other way to split a combined interface object into 2 objects?

5 messages · Page 1 of 1 (latest)

unique vortex
#

Is there any other way to split a combined interface object into 2 objects? I thought of these, but I would like a more automatic one.
Example:

interface Interface1 {
  name: string;
  age: number;
}

interface Interface2 {
  address: string;
  phone: number;
}

interface CombinedInterface extends Interface1, Interface2 {
}

const example: CombinedInterface = {
  name: 'John Doe',
  age: 30,
  address: '123 Main St',
  phone: 1234567890
};

To
1)

const interface1: Interface1 = {
  name: example.name,
  age: example.age
};

const interface2: Interface2 = {
  address: example.address,
  phone: example.phone
};
const { name, age } = example;
const interface1: Interface1 = { name, age };

const { address, phone } = example;
const interface2: Interface2 = { address, phone };

Looked for a more automatic way to do this 😦

shrewd reef
#

Do you want automatically split a combined type object?

#

like lodash.pick?

past gorge
#

@unique vortex TS types don't exist at runtime, so there's not going to be any way to use the definitions of Interface1 and Interface2 to directly pull properties from an object.

#

One thing to consider is whether you can get away with extra properties: i.e. can you do:

const interface1: Interface1 = example;
const interface2: Interface2 = example;

As far as TS is concerned, this is perfectly fine, and the language is built-around trying to prevent errors from this sort of thing.