type UpdateConsumerT = {
obj: {
min_quantity: number
fixed_price: number
date_start: string | boolean
date_end: string | boolean
}
}
type UpdateProducerT = {
obj: {
min_qty: number
price: number
date_start: string | boolean
date_end: string | boolean
}
}
export async function updatePricelistItem(
pricelist_item_id: number,
obj: UpdateConsumerT,
isProduction: false
): Promise<number>
export async function updatePricelistItem(
pricelist_item_id: number,
obj: UpdateProducerT,
isProduction: true
): Promise<number>
export async function updatePricelistItem(
pricelist_item_id,
obj,
isProduction = false
) { ... }
I have this function, and i try to use overloads
But for some reason it says
Parameter ‘pricelist_item_id’ implicitly has an ‘any’ type.ts(7006)
My question is, what am i doing wrong here?
3
Answers
You will need to explicitly specify the parameter types and return type on the implementation:
Playground
If you have noImplicitAny set to true in your tsconfig file, any function parameter without an explicitly declared type will be considered as implicitly any, leading to a compilation error.
You can fix that error by adding type annotation or add explicit any type
Example Playground
Overload function implementations do not currently have their parameter types inferred contextually from the call signatures. There’s a longstanding open feature request for this at microsoft/TypeScript#25352, but for now it’s not part of the language.
Until and unless that gets implemented, you will need to manually annotate the function implementation’s parameters:
Do note that because your call signatures return the same type for each call, you don’t need to use overloads. Instead you can use a rest parameter whose type is a union of tuple types:
This approach is even better for your implementation because that rest parameter is a discriminated union with
isProduction
as the discriminant, so you can use control flow analysis on the destructured parameters to narrowobj
based onisProduction
:Playground link to code