typescript - 具有多个参数的函数接口?
问题描述
我有一个函数,其中第一个参数必须是字符串。之后可以有无限数量的参数或根本没有参数:
const myFunction = (arg1: string, ...rest: any) {
// do stuff
}
我可以创建一个同时指定arg1
和的类型或接口...rest
吗?我问其他函数有相同的参数,我想重用打字。
解决方案
您可以通过从具有最小长度的 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[]]'.
推荐阅读
- group-by - SAS:一次按组对所有变量进行频率处理?
- sql-server - 链接到 SQL Server 的访问显示 #Name? 在过滤后的字段中
- .net - 无法从 .NET 框架 WPF 应用程序将 .NET Standard 类库作为 NuGet 包引用
- sql - 在 eventTime 中触发结构化流式 sql 窗口
- postgresql - Hasura - “看起来你没有任何桌子”
- teradata - 太数据错误 2641
进行了重组。重新提交 - c# - Jmeter - Azure AD - Bearer Token - 配置函数
- sql - 使用过滤后的 GroupBy 查询返回零计数
- python - 将基于索引的列添加到 Pandas 中的数据框
- php - PHP正则表达式用回调替换多个模式