When I try to overload this function with different callback params i run into an error This overload signature is not compatible with its implementation signature.ts(2394) database.ts(41, 3): The implementation signature is declared here.
listen(onData: (data: number) => void): void
listen(onData: (data: number[]) => void): void
listen(onData: (data: number | number[]) => void): void {
...
}
According to this q Typescript: specifying multiple callback types in a union it appears that you can do it, so I'm not sure where I'm going wrong.
Edit: The actual implementation of the function:
listen(
ref:
| firebase.firestore.DocumentReference
| firebase.firestore.CollectionReference,
onData: (data: ReadData<T> | ReadData<T>[]) => void
): () => void {
return ref instanceof firebase.firestore.DocumentReference
? ref.onSnapshot((doc) => onData(this.txDocData(doc)))
: ref.onSnapshot((snap) => onData(snap.docs.map(this.txDocData)))
}
The callbacks are different types. They are not compatible. They just happen to be functions.
function listen(onData: (data: number) => void): void
function listen(onData: (data: number[]) => void): void
function listen(onData: ((data: number) => void) | ((data: number[]) => void)): void {
onData([42]); //Argument of type 'number[]' is not assignable to parameter of type 'number & number[]'.
// Type 'number[]' is not assignable to type 'number'.(2345)
onData(42); //Argument of type 'number' is not assignable to parameter of type 'number & number[]'.
// Type 'number' is not assignable to type 'number[]'.(2345)
}
Try to think the other way around: If I call listen()
with a cb that expects to be called with a number[]
it must not be called with a number
by the implementation. I declared that cb can only be called with a number[]
. The same goes the other way.
The only solution for the compiler is to enforce that onData is called with a parameter that is a number
and a number[]
at the same time - hence the type number & number[]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.