首页 > 解决方案 > 具有多个参数的函数接口?

问题描述

我有一个函数,其中第一个参数必须是字符串。之后可以有无限数量的参数或根本没有参数:

const myFunction = (arg1: string, ...rest: any) {
  // do stuff
}

我可以创建一个同时指定arg1和的类型或接口...rest吗?我问其他函数有相同的参数,我想重用打字。

标签: typescript

解决方案


您可以通过从具有最小长度的 TypeScript 数组中获取答案并将其用作 rest 参数的类型来做到这一点,例如:

type OneOrMore<T> = { 0: T } & Array<T>;

// or allow the rest to be a wider type, like any:
// type OneOrMore<T, S extends T = T> = { 0: T } & Array<S>;

您可以使用以下方法定义函数类型

type MyFunction = (...args: OneOrMore<string>) => void;

const myFunction: MyFunction = (...args) => { /* use args */ };

或直接使用:

function anotherFunction(...args: OneOrMore<string>) { /* use args */ }

现在允许使用一个或多个参数调用,但不带参数调用会给出例如

Argument of type '[]' is not assignable to parameter of type 'OneOrMore<string>'.
  Property '0' is missing in type '[]' but required in type '{ 0: string; }'.

操场


但是,请注意,您的实现不能独立命名第一个参数;以下:

const myFunction: MyFunction = (arg, ...args) => { /* use arg and args */ };

结果是:

Type '(arg: string, ...args: string[]) => void' is not assignable to type 'MyFunction'.
  Types of parameters 'arg' and 'args' are incompatible.
    Type 'OneOrMore<string>' is not assignable to type '[arg: string, ...args: string[]]'.

推荐阅读