【发布时间】:2020-02-19 10:27:33
【问题描述】:
在标题中有点难以解释,但基本上,我希望能够声明一个从 1 到 N 的固定长度字符串的类型数组:
interface Command {
[key: string]: (args: [string, ...string[]]) => boolean;
}
const cmd: Command = {
TEST: (args: [string, string]) => args[0] === args[1],
TEST2: (args: [string]) => args[0] === 'hello'
}
所以这不起作用,因为 [string, string] 与 string[] 不同:
Type '(args: [string]) => boolean' is not assignable to type '(args: [string, ...string[]]) => boolean'.
解决方案可能是定义所有类型的参数:
interface Command {
[key: string]: (args: [string] | [string, string] | [string, string, string]) => boolean;
}
但是对于简单的事情来说有点过于冗长(同意它可以封装在一个接口中),无论如何我没有看到另一个优雅的解决方案?
谢谢,
【问题讨论】:
-
不,这是不可能的。 Typescript 不支持具有指定字符串长度的类型。但也许有些东西可以帮助你,看看这个答案:stackoverflow.com/a/54832231/7616528
-
您的“冗长”解决方案也不起作用,对吧?它给出了同样的错误。我不太确定您希望
Command看起来像什么。你能说明你打算如何使用c类型为Command的值吗?说,你有函数c.f...你可以用c.f(["hello"])调用它吗?你能用c.f(["hello","goodbye"])打电话吗?
标签: typescript typescript-typings