Typescript 具有多种可能性的函数的返回类型

Typescript 具有多种可能性的函数的返回类型,typescript,typescript-typings,typescript-generics,Typescript,Typescript Typings,Typescript Generics,TS如何知道具有多个返回类型的函数的返回类型,如: type VariantA = Variant & { a: number, b: string, c: string[] } type VariantB = Variant & { e: number, f: string, g: string[] } const CreateObject = (type: 'variantA' | 'variantB') => {

TS如何知道具有多个返回类型的函数的返回类型,如:

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
    }
}
在这里,如果编辑器能够告诉我是否将“variantA”作为类型传递,那么返回类型是variantA else VariantB,那就太酷了。有可能吗?

啊,我解决了(但可能有更好的选择?)

所以我只是创建了一些重载:

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
    }
}

现在TS将选择最佳选项(希望是lol)

您可以创建两个接口,并使用Union类型a返回类型

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);

但是在这种情况下,TS不会给objectA类型:VariantA | VariantB,而不是具体说明它并将其作为返回类型吗?会的,这就是为什么@aaron beall对您的答案的注释修复是正确的解决方案。非常接近,制作第一个签名
(type:'typeA'):VariantA
,第二个
(type:'typeB')):VariantB
和now调用将获得返回类型
VariantA
VariantB
,具体取决于参数。