Recently, I've encountered an issue while trying to overload function in TypeScript. Interestingly, my function arguments are being highlighted with the any
type for some reason.
This is what I am attempting to accomplish:
I have defined two types for objects:
type SomeObj = {
prop: number
}
and
type AnotherObj = {
anotherProp: string
}
Here is my function:
interface SomeFunc {
<T = AnotherObj>(a: T, b: true): T & SomeObj;
<T = AnotherObj>(a: T, b?: boolean): T;
}
Now, let's look at how this function is implemented:
let someObj: SomeObj = {
prop: 42
}
let someFunc: SomeFunc = function(a, b) {
if (b === true) return Object.assign({}, a, someObj);
else return a
}
var x = someFunc({ anotherProp: '1' }, true)
var y = someFunc({ anotherProp: '1' })
This function returns merged objects (AnotherObj & SomeObj
) when the second argument is true. Otherwise, it simply returns the first argument AnotherObj
.
Despite getting the correct highlights when checking the results of x
and y
, TypeScript still gives me a warning that function arguments are implicitly any
. However, it is evident that the first argument is of type AnotherObj
and the second argument is of type boolean | undefined
.
What changes can be made to the function interface declarations to resolve this warning? You can also view the code on TS playground