Having some trouble with one of my TypeScript functions and I'm hoping it's not a silly question. I believe what I'm attempting should work in theory.
Here's a simplified version of my issue to demonstrate where the problem lies (the original code is too lengthy).
abstract class A {
name: string;
log(callback: (ev: A) => void) {}
constructor(name: string) {
this.name = name;
}
}
class B extends A {
addr: string;
constructor(addr: string, name: string) {
super(name);
this.addr = addr;
}
}
let b = new B("1", "2");
b.log((ev: B) => {});
The issue arises in the last line of code. The log
function is a callback with type A
, but I am trying to call it with an attribute of type B
. This should theoretically work because B extends A
, but I'm getting the following error:
Argument of type '(ev: B) => void' is not assignable to parameter of type '(ev: A) => void'.
Types of parameters 'ev' and 'ev' are incompatible.
Property 'addr' is missing in type 'A' but required in type 'B'.(2345)
input.tsx(13, 5): 'addr' is declared here.
I'd rather not cast my ev
parameter in the function. Hopefully, you understand the issue and my objectives.
Have a wonderful day.