繁体   English   中英

打字稿:只键入函数的参数或返回类型

[英]Typescript: typing only the arguments or the return type of a function

我有几个函数接受不同的参数,但它们都返回一个具有相同签名的函数:

const createSum5 = () => (c: number) => c + 5;
const createMultiplyN = (n: number) => (c: number) => n * c;
const createWordsSum = (word: string) => (c: number) => word.length + c;

返回类型始终是(c: number) => number 有没有办法可以为所有函数键入此返回值,而无需键入参数? 这样我就可以在不丢失类型安全的情况下缩短它们:

createSum5: /* Something here */ = () => c => c + 5;


我试过这些,但是:

1.此解决方案失去了类型安全性: type NumericArg = (...args: any) => (c: number) => number ;

2.我可以事先为每个函数编写函数签名:

type Nfunction = (c: number) => number;
type createSum5Type = () => Nfunction;
...
const createSum5: createSum5Type = () => c => c + 5;

但那将是乏味的。 如果我不指定类型,我希望Typescript自动推断参数。

还有其他方法吗? 可以相反完成(指定具有相同签名的函数,但让Typescript推断返回类型?)。


编辑#1:这是我说的相反的例子:

const func1: /* Something here */ = num => '#'.repeat(5);
const func2: /* Something here */ = num => num * num;

func1和func2都具有相同的签名(num: number)但返回类型不同。 我希望Typescript推断每次调用func1时返回类型都是一个string ,但是对于func2 ,返回类型是一个数字。


编辑#2:

我的用例不相关,但无论如何我都会添加它。 我正在使用Thunks开发一个React-redux应用程序。 每个thunk总是返回一个带签名(dispatch, getState) => void的函数,但它们可以接受不同的参数。 经过一些研究,这是我能找到的不那么冗长的版本:

const onFetchUser = (userIds: number[]) : ThunkFunction = dispatch => { ... }

如果有一种方法允许Typescript推断参数,但让我设置返回类型(这是我的问题),我可以让它更容易阅读:

const onFetchUser: /* something here */ = (userIds: number[]) => dispatch => {...}

不确定它是否是唯一的选项,但是一个选项是使用辅助函数,该函数具有一个通用参数,该参数将捕获传入的函数的实际类型,但也将强制执行返回类型(c: number)=> number

function fn<T extends (...a: any[]) => (c: number) => number>(o: T) {
  return o;
}
const createSum5 = fn(() => c => c + 5)
const createMultiplyN = fn((n: number) => c => n * c);
const createWordsSum = fn((word: string) => c => word.length + c);

我不相信存在另一个选项,typescript通常不允许对变量进行部分推理(或者更具体地说是约束推理),这只能通过函数来​​完成。

TypeScript支持关键字infer ,它允许您保留函数的参数类型和/或返回类型。

对于条件类型,它看起来像这样:

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

这里有一些关于推断的信息: https//www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html

更新:

您只需使用通用函数即可:

type numFunc<T> = (arg: T) => (c: number) => number; 

const createSum5: numFunc<void> = () => (c: number) => c + 5;
const createMultiplyN: numFunc<number> = (n: number) => (c: number) => n * c;
const createWordsSum: numFunc<string> = (word: string) => (c: number) => word.length + c;

const createSumString: numFunc<number> = () => (c: number) => 'Hello';  //error

暂无
暂无

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

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