首页 > 解决方案 > 用于作为函数参数的可选值组的打字稿

问题描述

我有一个将任意数量的分组值作为参数的函数。我认为最好的方法是传入数组(但对其他选项开放)。每个数组可以有 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 ","

如果我删除了?我没有得到编译错误,但它期望数组中的所有值都被传递。

有一个简单的解决方案吗?

标签: javascripttypescript

解决方案


 // 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
};

推荐阅读