我想向用户介绍更好的 api 以通过键获取值。这个想法是允许将键作为数组传递或作为列一个接一个地传递。例如:
mget('key1', 'key2', 'key3');
mget(['key1', 'key2', 'key3']);
我尝试过的实现,它实际上大部分时间都有效
async mget(...keys: string[]): Promise<StorageValue>;
async mget(keys: string[]): Promise<StorageValue>;
@requireStorage
async mget(firstArg: string | string[], ...rest: string[]): Promise<Array<StorageValue>> {
const keys = Array.isArray(firstArg) ? firstArg : Array(firstArg, ...rest);
// do something with keys
}
但问题是当函数调用时没有任何键,比如
mget()
所以我得到 keys===[undefined]
因为 firstArg
没有定义所以它用 undefined
参数创建新数组。
虽然我可以解决这个问题,但它变得更丑陋且容易出错。我对一种更好、更简单的方法很感兴趣,可以实现如此简单的重载,而这在 TS 中根本就不那么容易。
我觉得你可以做到
@requireStorage
function mget(...args: [string[]] | string[]): Promise<Array<StorageValue>>
...
}
args 数组包含单个字符串数组或多个字符串。
这里是一个Playground