Istvan Orban
Istvan Orban

Reputation: 1685

Telling return type of function with multiple possibilities

how could TS know the return type of functions with multiple return type like:

type VariantA = Variant & {
    a: number,
    b: string,
    c: string[]
} 

type VariantB = Variant & {
    e: number,
    f: string,
    g: string[]
}

const CreateObject = (type: 'variantA' | 'variantB') => {
    if (type === 'variantA') {
        return { a: 5, b: 'hello', c: ['a', 'b'] } as VariantA
    } else {
        return { e: 5, f: 'hello', g: ['a', 'b'] } as VariantB
    }
}

Here its would be cool if the editor could tell if I pass 'variantA' as type, then the return type is VariantA else VariantB. Is it possible?

Upvotes: 0

Views: 51

Answers (2)

henrik123
henrik123

Reputation: 1683

You could create two interfaces and the use the Union type a return type.

interface VariantA{
  a: number,
  b: string,
  c: string[]
}

interface VariantB{
  e: number,
  f: string,
  g: string[]
}

type Variants = VariantA | VariantB;

const createObject = (type: string): Variants => {
  if (type === 'variantA') {
      return { a: 5, b: 'hello im variant A', c: ['a', 'b'] }
  } else {
      return { e: 5, f: 'hello im variant B', g: ['a', 'b'] }
  }
};

const objectA = createObject('variantA');
const objectB = createObject('variantB');
console.log(objectA);
console.log(objectB);

Upvotes: 0

Istvan Orban
Istvan Orban

Reputation: 1685

Ah I solved it (but there are might better alternatives?)

So I just created a few overloads:

function CreateObject(type: 'typeA' | 'typeB'): VariantA
function CreateObject(type: 'typeA' | 'typeB'): VariantB
function CreateObject(type: 'typeA' | 'typeB'): VariantA | VariantB {
    if (type === 'typeA') {
        return { a: 1, b: '2', c: ['3', '4'] } as VariantA
    } else {
        return { e: 1, f: '2', g: ['3', '4'] } as VariantB
    }
}

Now TS gonna choose the best option (hopefully lol)

Upvotes: 1

Related Questions