Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript是否可以为1-N个字符串的数组声明泛型类型_Typescript_Typescript Typings - Fatal编程技术网

Typescript是否可以为1-N个字符串的数组声明泛型类型

Typescript是否可以为1-N个字符串的数组声明泛型类型,typescript,typescript-typings,Typescript,Typescript Typings,在标题中有点难解释,但基本上,我希望能够声明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]

在标题中有点难解释,但基本上,我希望能够声明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'不可分配给Type'(args:[string,…string[])=>boolean'。

解决方案可以是定义类似于所有类型的参数:

interface Command {
  [key: string]: (args: [string] | [string, string] | [string, string, string]) => boolean;
}
但是对于一些简单的东西来说有点太冗长了(同意它可以封装在一个接口中),无论如何,有没有其他优雅的解决方案我没有看到


谢谢,

我怀疑您实际上需要
命令
,以便它的属性可以实际使用。如果您有一个函数类型,如
(arg:[string]|[string,string])=>boolean
,则不能使用
(arg:[string])=>boolean
(arg:[string,string])=>boolean来实现它。函数类型因其参数类型而异。可以扩大但不能缩小函数参数的类型。除非您想要求所有
Command
类型的方法必须接受长度为一个或多个的所有可能字符串数组,否则必须使用泛型

下面是
Command
的一种可能类型,以及一个助手函数
asCommand()
,它允许编译器在给定
Command
类型值的情况下推断
T
的正确值,而不必强迫您自己写出它:

type Command<T> = { [K in keyof T]: (args: T[K]) => boolean }

const asCommand = <T extends Record<keyof T, [string, ...string[]]>>(
    cmd: Command<T>
) => cmd;
编译器记住
cmd.TEST
取一对,而
cmd.TEST2
取一个元组:

cmd.TEST(["", ""]); // okay
cmd.TEST([]); // error
cmd.TEST([""]); // error
cmd.TEST(["", "", ""]); // error

cmd.TEST2([""]); // okay
cmd.TEST2([]); // error
cmd.TEST2(["", ""]); // error
cmd.TEST2(["", "", ""]); // error
并且不允许您提供只接受零长度元组的属性:

const badCmd = asCommand({
    OOPS: (args: []) => false, // error!
})
我希望这能给你一些指导;祝你好运


不,这是不可能的。Typescript不支持具有指定字符串长度的类型。但也许有些东西可以帮助你,看看这个答案:你的“冗长”解决方案也不起作用,对吧?它给出了同样的错误。我不太确定您希望
Command
看起来像什么。您能否说明您计划如何使用
Command
类型的值
c
?比如说,你有功能
c.f
。。。您可以用
c.f([“hello”])调用它吗?你能用c.f([“你好”,“再见])来称呼它吗?
const badCmd = asCommand({
    OOPS: (args: []) => false, // error!
})