javascript - 用于作为函数参数的可选值组的打字稿
问题描述
我有一个将任意数量的分组值作为参数的函数。我认为最好的方法是传入数组(但对其他选项开放)。每个数组可以有 1-4 个必须匹配特定类型的值。我编写代码的尝试如下所示:
const transition = (...properties: [string, number?, string?, number?][]): string => {
// Do something
};
用法可能如下所示:
transition(['color', 2]);
transition(['color', 2], ['background']);
transition(['color', 2], ['background', 2, 'ease']);
transition(['color', 2], ['background'], ['opacity', 3, 'ease']);
我的编译器抛出与?
类型中的用法相关的错误:
SyntaxError: Unexpected token, expected ","
如果我删除了?
我没有得到编译错误,但它期望数组中的所有值都被传递。
有一个简单的解决方案吗?
解决方案
// Declare a type for arguments
export interface ITransitionProperties {
color: string,
value?: number,
type?: string,
value2?: number
}
// and use it in defining the type of argument
const transition = (ArgumentName: ITransitionProperties[]): string => {
// Do something
};
推荐阅读
- android - 评估项目 ':app' 时出现问题。> ASCII
- php - 如何通过输入特定月份的数据来限制用户,其中 Yii2 中存在大于特定月份的记录
- llvm - 为什么将 8 对齐为 int?
- java - Spring bean后处理器:注入一个值
- javascript - 逐步聚焦 TextInput 反应原生
- sql - 使用公用表表达式删除查询(“WITH AS”子句)
- c# - Unity - 关于 AnimationMode 和 GetCurveBindings 的错误 CS0117
- c# - 使用 C# 设置默认的全局打印首选项
- xslt - XSLT 2.0 版日期问题
- javascript - 点击 td 函数时获取表的 ID