首页 > 解决方案 > 如何将“string[]”类型的数组分配给“[string, ...string[]]”类型的非空数组

问题描述

我有一个定义如下的接口。它是可重用 NPM 模块的一部分。模块内一切正常,我的单元测试工作,我可以使用创建设置[ "value" ]

export interface Settings {
  nonEmptyArrayProperty: [string, ...string[]]
}

但是我有另一个模块导入这个包,我试图从里面定义设置。我收到以下错误:

Type 'string[]' is not assignable to type '[string, ...string[]]'.

我的设置在一个 js 文件中,但在属性名称方面是相同的:

export const SETTINGS= {
    nonEmptyArrayProperty: ["value1", "value"],
};

需要注意的一点是,我正在使用扩展运算符将 JS 设置转换为我的库中定义的设置接口。

如何将 string[] 分配给 [string, ...string[]]?

标签: javascripttypescript

解决方案


打字稿不允许这样做的原因是因为类型[string, [...string]]意味着该值至少包含一个字符串,而string[]可以包含0。所以当涉及到赋值行时,打字稿只知道它是a string[],所以它认为它可能是空的(如果对我们来说很明显不是)。

如果您事先指定分配给设置对象的变量的类型,就不会遇到这种麻烦。在打字稿中,这意味着您可以在分配变量时执行以下操作:

const nonEmptyArray = ["value1", "value"] as const;

但是,如果您这样做(如评论中所指出的)从无类型的 javascript 文件中获取变量,则必须更具体地使用类型,如下所示:

export const SETTINGS= {
    nonEmptyArrayProperty: nonEmptyArray as [string, ...string[]],
};

推荐阅读