繁体   English   中英

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

[英]How to specify typescript conditional type based on a function return type in the arguments

我有一个这样的功能:

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

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

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

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

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

这是选项类型的定义:

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

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

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

const myFunc = (data: MyType): string => {
  return data.someProperty;
};

const myFunc = (data: MyType): MyType => {
  return data;
};

我认为最接近的方法是键入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 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM