Home > front end >  typescript, create type combine option value
typescript, create type combine option value

Time:11-12

In typescript.

I have a type A:

interface A {
    a1: string;
    a2: int;
}

And a B:

interface B {
    b1: number
}

And now I want a type:

interface AB {
    a1?: string;
    a2?: string;
    b1: string;
}

Which combine all A option value and B

How can I do this in typescript?

CodePudding user response:

This has been answered previously here: Merge Two Interfaces, the only difference is the usage of a Partial which Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.:

You can either create a new interface:

interface Ci extends Partial<A>, B {}

or create a type:

type Ct = Partial<A> & B

Try the following on the typescript playground:

interface A {
  a1: string
  a2: number
}

interface B {
  b1: number
}

interface Ci extends Partial<A>, B {}

type Ct = Partial<A> & B

const interfaceType: Ci = {a1: 'blah', a2: 1, b1: 2}

const typeType: Ct = {a1: 'blah', a2: 1, b1: 2}

const partialInterfaceType: Ci = {b1: 1}

const partialTypeType: Ci = {b1: 1}

console.log('interfaceType', interfaceType)
console.log('typeType', typeType)
console.log('partialInterfaceType', partialInterfaceType)
console.log('partialTypeType', partialTypeType)

or check out the playground I've already created for an example: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgILIN4ChnLgRgC5kBnMKUAcxzwCZiQBXAWwCNosBfLLUSWRCgBCmGqyLImbDt17ho8JMgDCwZBAAekEABMSyAApwoYYHAA2AHlQA ADTIRGWWACeABxTKwyALyHjUwtrG2QAMkceBAB7EDJkPgVBABUPCGJVP0wCYgByVnM4AAtchzh6ZHwHcWJaWRi4nzdPVM8Mn38MHOR8wpKyiqrkGuQ6qNj490CzcwBJeQEkVvSVNU6R-HqJnymTGeXljLXMDa246PMIADpzaMoAClzExYhl0oSFxVe0gEosBpIF2utweuWa30873Byz AKBNzuj12QTmnxSaXeyJm834Xxh-wm8JBSOmFgOGIcWLJaRhQA

  • Related