我有这样一门课:
type Params = {
data: string | string[]
}
class Test {
data: string | string[]
constructor(params: Params) {
this.data = this.initData(params.data)
}
initData(data: string): string
initData(data: string[]): string[]
initData(data: string | string[]): string | string[] {
if (typeof data === 'string') {
return data as string
} else {
return data as string[]
}
}
}
但我得到了这样的错误:
No overload matches this call.
Overload 1 of 2, '(data: string): string', gave the following error.
Argument of type 'string | string[]' is not assignable to parameter of type 'string'.
Type 'string[]' is not assignable to type 'string'.
Overload 2 of 2, '(data: string[]): string[]', gave the following error.
Argument of type 'string | string[]' is not assignable to parameter of type 'string[]'.
Type 'string' is not assignable to type 'string[]'.ts(2769)
Untitled-1(38, 5): The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.
我发现了一个愚蠢的变通办法,它有帮助:
constructor(params: Params) {
this.data = this.initData(params.data)
if (typeof params.data === 'string') {
this.data = this.initData(params.data)
}
else {
this.data = this.initData(params.data)
}
}
我有点明白为什么这是可行的,但也许有更好的方法来解决这个问题?