{ if (n) return array-6ren">
gpt4 book ai didi

javascript - 为什么我在使用 Array concat 时不断收到 TypeScript 错误 "No overload matches this call"?

转载 作者:行者123 更新时间:2023-12-05 00:39:27 47 4
gpt4 key购买 nike

我写了一个函数来获得第一个 n数组中的项目:

export const first = <T>(array: T[], n?: number): T[] => {
if (n) return array.slice(0, n)
return [].concat(array).shift()
}

这里是 link要重现的脚本。

编译器返回错误
error TS2769: No overload matches this call.
Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'T[]' is not assignable to parameter of type 'ConcatArray<never>'.
The types returned by 'slice(...)' are incompatible between these types.
Type 'T[]' is not assignable to type 'never[]'.
Type 'T' is not assignable to type 'never'.
Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'T[]' is not assignable to parameter of type 'ConcatArray<never>'.

return [].concat(array).shift()

当我查看 lib.es5.d.ts带有 VSCode 的文件, concat接受两个重载参数。
concat(...items: ConcatArray<T>[]): T[];
concat(...items: (T | ConcatArray<T>)[]): T[];

通过看到第二种调用,我尝试更改 first的第一个参数函数来自 array: T[]array: (T | ConcatArray<T>)[]但随后它返回错误,
Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type '(T | ConcatArray<T>)[]' is not assignable to parameter of type 'ConcatArray<never>'

我应该怎么做才能修复这些错误?
我是 TypeScript 的新手,如果这是一个愚蠢的问题,请原谅我。

最佳答案

In this github issue you can see why the array have a never type ,主要 react 是:

This is caused by the combination of strict and noImplicitAny: false. In general we expect that if strict is on, noImplicitAny is also on; this particular set of settings will expose some odd behavior. If you had both on, you'd see an error about the [] being implicitly any[]; if both were off; we'd use control flow analysis and treat the array as a number[] after the push(1);.

The particular combination of settings means that we don't allow ourselves to use control flow analysis or allow the array to be implicitly any[], so never[] is the only remaining allowable option.

I'd recommend turning off strict if you're not going to have noImplicitAny on.


关于如何解决您的问题,您可以使用我写的两种方法中的任何一种 in this TS playground ,我推荐你第二个,因为你会考虑到函数返回的两个可能的值,第一个你只是用类型断言欺骗 TS 以返回 T[],但是当数组没有时,类型可能是未定义的没有值(value)。
const second = <T>(array: T[], n?: number): (T | undefined)[] => {
if (n) return array.slice(0, 2)

return [array.shift()]
}

关于javascript - 为什么我在使用 Array concat 时不断收到 TypeScript 错误 "No overload matches this call"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61283364/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com