TypeScript类静态方法重载报错:重载签名与实现不兼容
解决TypeScript重载签名不兼容的报错
你遇到的问题根源在于实现签名的参数没有标记为可选。虽然你把后两个参数的类型设为包含undefined,但TypeScript里,参数允许undefined和参数是可选参数是两回事——前者要求调用时必须传这个参数(哪怕传undefined),后者才允许不传参数。
你的重载签名里有只传1个、2个参数的情况,但原实现签名要求必须传3个参数(后两个可以是undefined但不能省略),这就导致重载签名和实现签名不兼容,触发报错。
解决方法
把实现签名里的后两个参数加上?标记,明确它们是可选参数:
export class FullId { // other stuff static parse(toParse: string): FullId; static parse(toParse: string, withIdType: 'U' | 'S' | 'O' | 'T'): FullId; static parse( toParse: string, withIdType: 'U' | 'S' | 'O' | 'T' | undefined, withEntityType: string | undefined ): FullId; static parse( toParse: string, withIdType?: 'U' | 'S' | 'O' | 'T' | undefined, withEntityType?: string | undefined ): FullId { // my implementation } }
简化写法补充
其实可选参数本身就隐含了undefined,所以可以把类型里的| undefined去掉,写法更简洁:
export class FullId { // other stuff static parse(toParse: string): FullId; static parse(toParse: string, withIdType: 'U' | 'S' | 'O' | 'T'): FullId; static parse( toParse: string, withIdType: 'U' | 'S' | 'O' | 'T', withEntityType: string ): FullId; static parse( toParse: string, withIdType?: 'U' | 'S' | 'O' | 'T', withEntityType?: string ): FullId { // my implementation } }
这样修改后,所有重载签名都能被实现签名兼容,编译器就不会再报错了。
内容的提问来源于stack exchange,提问作者NotX
相关产品推荐
相关产品推荐

