有人可以在这里向我解释 TypeScript 的行为吗?
JavaScript
const test1 = [
['a', 'b'],
['c', 'd'],
];
const test2 = [
...[
['a', 'b'],
['c', 'd'],
],
];
console.log(JSON.stringify(test1) === JSON.stringify(test2));
true
按预期记录(数组相同)。
打字稿
const test1: [string, string][] = [
['a', 'b'],
['c', 'd'],
];
const test2: [string, string][] = [
...[
['a', 'b'],
['c', 'd'],
],
];
但是,这会导致以下错误test2
:
Type 'string[][]' is not assignable to type '[string, string][]'.
Type 'string[]' is not assignable to type '[string, string]'.
Target requires 2 element(s) but source may have fewer.
这是TypeScript Playground 上的复制器。
我在这里做错了什么,或者有什么方法可以让这个工作而不诉诸一些丑陋的类型转换?
这是我试图实现的一个更具体的例子:
const someValues = [1, 2, 3];
const test3: [string, string][] = [
...someValues.map(value => ['some string', 'another string']),
];
按照 Алексей Мартинкевич 的建议,我可以确认这是有效的:
const someValues = [1, 2, 3];
const test3: (readonly [string, string])[] = [
...someValues.map(i => ['a', 'a'] as const),
];
不过,会有更易读/更简单的解决方案吗?
(想到我的同事和未来 2 周的我想知道我在那里做了什么:D)
对于您的具体具体情况,您可以在给定的箭头函数上指明返回类型map
:
const someValues = [1, 2, 3];
const test3: [string, string][] = [
...someValues.map((value): [string, string] => ['some string', 'another string']),
];
如果您认为它足够明确,您还可以删除变量上的类型:
const test4 = [
...someValues.map((value): [string, string] => ['some string', 'another string']),
];
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句