告诉函数返回类型有多种可能性

时间:2019-05-31 12:45:10

标签: 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') => {
    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,否则返回VariantB。有可能吗?

2 个答案:

答案 0 :(得分:1)

啊,我解决了(但是还有更好的选择吗?)

所以我刚刚创建了一些重载:

Work Orders Started This Week:=
VAR WeekCommencing = TODAY() - WEEKDAY(TODAY(),3)
VAR WeekEnding = WeekCommencing + 6
RETURN
    CALCULATE ( 
        DISTINCTCOUNT ( Table_IS[Work Order] ),
        Table_IS[Date Started] >= WeekCommencing && Table_IS[Date Started] <= WeekEnding
    )

现在,TS会选择最佳选项(希望大声笑)

答案 1 :(得分:0)

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

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