[英]How to make type inference work when generic type can be recursively nested
I've just started working with function overloads.我刚刚开始使用 function 重载。
I have the following function defined with an overload.我定义了以下带有重载的 function。 However, when the function is used, the generic type T
is not always inferred properly.但是,当使用 function 时,泛型类型T
并不总是正确推断。
function arrayWrapper<T>(input: T): T[];
function arrayWrapper<T>(input: T[]): T[];
function arrayWrapper<T>(input: T | T[]): T[] {
if (input instanceof Array) {
return input;
}
return [input];
}
For example, this code例如,这段代码
function arrayWrapperExample(): string[] {
return arrayWrapper(['hello']); // Error here
}
produces this inference error:产生这个推理错误:
Type 'string[][]' is not assignable to type 'string[]'.
Type 'string[]' is not assignable to type 'string'.ts(2322)
However, if I explicitly specify the generic type of promiseWrapper
, the error resolves.但是,如果我明确指定promiseWrapper
的通用类型,错误就会解决。
function arrayWrapperExample(): string[] {
return arrayWrapper<string>(['hello']);
}
But this is redundant, because the return type has already been specified once, as the return type of the function.但这是多余的,因为返回类型已经指定了一次,如function的返回类型。
Can the overloads of arrayWrapper
be declared in such a way that I don't need to specify string
a second time? arrayWrapper
的重载是否可以以不需要再次指定string
的方式声明?
Thanks in advance!提前致谢!
The first overload that matches your parameters is taken, so just put them in order of priority (from the most specific to the most generic):第一个与您的参数匹配的重载被采用,所以只需将它们按优先级排序(从最具体到最通用):
function arrayWrapper<T>(input: T[]): T[];
function arrayWrapper<T>(input: T): T[];
function arrayWrapper<T>(input: T | T[]): T[] {
if (input instanceof Array) {
return input;
}
return [input];
}
function arrayWrapperExample(): string[] {
return arrayWrapper(['hello']); // Error here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.