如何基于参数中的函数返回类型指定打字稿条件类型

时间:2019-04-11 18:38:11

标签: typescript

我有这样的功能:

TextField

现在,返回类型是字符串或MyType。

这是因为someFunction可以返回字符串或MyType。

是否有一种方法可以使用TypeScript条件类型根据someFunction实际返回的内容返回正确的类型?

[第一篇文章发表后的其他信息]

这是选项类型的定义:

export const getValue = (
  options: Options = { someMapping, someFunction }
): string | MyType => {
  ...
  return someFunction({ ...someData });
};

someFunc参数是一个需要MyType参数的函数。

根据情况,我传入了两个实际函数:

export interface Options {
  someMapping: MappingType;
  someFunc: (data: MyType) => MyType | string;
}

2 个答案:

答案 0 :(得分:1)

我认为最接近的方法是键入someFunction并使用函数重载。 Options使其变得更加复杂,但是应该可以进行以下操作:

type MyFunc<T extends MyType | string> = () => T;

interface Options<T extends MyType | string> {
  someMapping: WhateverTypeThisIs;
  someFunc: MyFunc<T>;
}

function getValue(options: Options<MyType>): MyType;
function getValue(options: Options<string>): string;
function getValue<T extends MyType | string>(options: Options<T>): T {
   return options.someFunc();
}

所以现在您应该为以下内容输入内容:

const myTypeOptions: Options<MyType> = {
   someMapping: {},
   someFunc: () => ({ myParam: "MyValue" })
};
const myStringOptions: Options<string> = {
   someMapping: {},
   someFunc: () => "Hello"
};
const myTypeValue = getValue(myOptions); // myNumberValue is of type { myParam: string };
const myStringValue = getValue(myStringOptions); // myStringValue is a string;

这当然取决于所讨论的函数总是返回MyType总是返回string的事实。如果它根据函数的参数而变化,则它将始终是MyType | string,因为Typescript无法确定。呼叫者要弄清楚它是什么。

编辑:

根据您介绍的场景,类似的方法可能会有所帮助。您可以创建为MyFunc类型。

type MyTypeFunc = (myType: MyType) => MyType;
type MyStringFunc = (myType: MyType) => string;

interface MyOptions {
  someMapping: WatheverTypeThisIs;
}

interface MyTypeOptions extends MyOptions {
  someFunc: MyTypeFunc;
}

interface MyStringOptions extends MyOptions {
  someFunc: MyStringFunc;
}

function getValue(options: MyTypeOptions): MyType;
function getValue(options: MyStringOptions): string;
function getValue(options: MyTypeOptions | MyStringOptions): T {
   return options.someFunc();
}

现在,无论何时调用它,您都可以创建或类似以下的选项:

const myTypeOptions: MyTypeOptions = {
  someMapping: {},
  someFunc: (myType) => myType
}

const myStringOptions: MyStringOptions = {
  someMapping: {},
  someFunc: (myType) => myType.someProperty
}

const myTypeValue = getValue(myTypeOptions); // myTypeValue will be of type MyType
const myStringValue = getValue(myStringOptions); // myStringValue will be of type string

答案 1 :(得分:0)

playground,您可以让Typescript推断返回类型。 @DeeV提供的函数重载也可以。

相关问题