Home > Mobile >  how to generate new type with re-use another type
how to generate new type with re-use another type

Time:08-21

In the example below how can I say type B should contains elements A, "id" is required but "key" and "value" are optinal

interface A {
  id: string;
  key: string;
  value: string | number;
}

/**
 * Type B should re-use interface A 
 * to correctly implement const sample
 */

type B = null;

const sample: B = { id: '1' };

CodePudding user response:

You can use utility types

interface A {
  id: string;
  key: string;
  value: string | number;
}

/**
 * Type B should re-use interface A 
 * to correctly implement const sample
 */

type B = Pick<A, 'id'> & Partial<Omit<A, 'id'>>

const sample: B = { id: '1' };

CodePudding user response:

Use Pick and Partial.

interface A {
  id: string
  key: string
  value: string | number
}

type B = Pick<A, 'id'> & Partial<Exclude<A, 'id'>>
  • Related