如何将string[]类型数组赋值给[string, ...string[]]非空数组类型
报错原因
[string, ...string[]] 是TypeScript定义的非空字符串元组类型,强制要求数组至少包含1个字符串元素;而你在JS文件中定义的数组默认会被TS推断为普通string[]类型,这类类型没有「非空」的属性保证,因此赋值时会触发类型不匹配错误。
解决方案
方案1:类型断言(适合确定配置永远非空的场景)
在TS侧接收配置做类型转换时,直接对数组做类型断言即可:
const settings: Settings = { ...SETTINGS, nonEmptyArrayProperty: SETTINGS.nonEmptyArrayProperty as [string, ...string[]] }
方案2:运行时非空校验(更稳妥的生产场景方案)
如果要避免配置为空导致的运行时问题,可以加一层类型守卫校验,同时满足类型检查和运行时安全要求:
// 定义非空校验函数 function assertNonEmptyStringArray(arr: string[]): asserts arr is [string, ...string[]] { if (arr.length < 1) { throw new Error('配置项 nonEmptyArrayProperty 必须至少包含1个字符串元素') } } // 转换配置前先调用校验 assertNonEmptyStringArray(SETTINGS.nonEmptyArrayProperty) const settings: Settings = { ...SETTINGS, nonEmptyArrayProperty: SETTINGS.nonEmptyArrayProperty }
方案3:JS侧加JSDoc类型标注
如果可以修改JS配置文件,直接给配置加JSDoc类型标注,让TS提前识别到正确类型:
/** * @type {{ nonEmptyArrayProperty: [string, ...string[]] }} */ export const SETTINGS = { nonEmptyArrayProperty: ["value1", "value"], };
内容的提问来源于stack exchange,提问作者Steve Fitzsimons
相关产品推荐
相关产品推荐

