TypeScript 函数参数泛型

标签 typescript typescript-typings typescript-generics

我正在尝试创建一个 TypeScript 函数,它接受一个数组并返回一个新函数,其中参数具有数组的类型。

换句话说,它应该是这样的:

type MyFunc = {
    <A>(arg: [A]): ((arg0: A) => any)
    <A, B>(arg: [A, B]): ((arg0: A, arg1: B) => any)
    <A, B, C>(arg: [A, B, C]): ((arg0: A, arg1: B, arg2: C) => any)
}

但对于可变数量的输入

具体示例

这里有一些具体的例子(尽管我正在寻找一般情况):

type MyFuncA = (arg: [number]) => ((arg0: number) => any)
type MyFuncB = (arg: [string]) => ((arg0: string) => any)
type MyFuncC = (arg: [number, string]) => ((arg0: number, arg1: string) => any)
type MyFuncD = (arg: [number, string, bool]) => ((arg0: number, arg1: string, arg2: bool) => any)

最佳答案

我认为最简单的是:

type MyFunc = <T extends readonly unknown[]>(args: T) => (...args: T) => unknown

它接受任何内容的数组作为 T,并使用 ...args: T 将该数组扩展到返回函数的参数上。

用法:

declare const fn: MyFunc // pretend this function exists

const testA = fn([1, 'asd', true] as const)
// (args_0: 1, args_1: "asd", args_2: true) => unknown

请注意,这里使用 as const 来强制参数为元组类型 [number, string, boolean],而不是 的数组类型>(number | string | boolean)[],因为它需要元组来推断参数的顺序。但提供任何元组类型都应该可以正常工作。

如果你不传入元组,你将提供一个扩展数组类型,它比没有好,但没有那么有用:

const testA = fn([1, 'asd', true])
// (...args: (string | number | boolean)[]) => unknown

Playground


如果您有一个元组类型,其中每个元素都有名称,这些名称甚至会被报告为函数的参数名称!

const myTuple: [num: number, str: string, isAwesome: boolean] = [1, 'asd', true]
const testA = fn(myTuple)
// (num: number, str: string, isAwesome: boolean) => unknown

这很整洁。

Playground

关于TypeScript 函数参数泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71898429/

相关文章:

angular - 错误 : InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

javascript - 通过 Promise.then 混契约(Contract)步和异步不起作用

typescript - 仅将 TypeScript 环境声明添加到特定文件(如 *.spec.ts)

TypeScript:为什么我不能分配类型为 { a: "a", b: "b"} 的对象的有效字段

typescript - 为对象的键添加前缀仅考虑重叠

typescript - 如何在 typescript 中使用 "fill in"泛型参数

typescript - 为什么declaration不能和typescript中的isolatedModules一起使用?

angularjs - 在 Sublime Text 3 中为 TypeScript 设置 AngularJS

javascript - 使用可能存在或可能不存在的接口(interface)修改全局

Typescript 在本地声明第三方模块