'Methods with different signatures in Typescript class inheritence
could someone explain why the following code snippet will introduce error please? Thank you!
class Base {
greet() {
console.log("Hello, world!");
}
}
class Derived extends Base {
// Make this parameter required
greet(name: string) { // why we have error here?
console.log(`Hello, ${name.toUpperCase()}`);
}
}
const b: Base = new Derived();
b.greet(); // why it crashes here?
I use Java a lot. So maybe I am thinking in a JAVA way. From my understanding, Derived class inherits great() method in Base class. When it defines greet(name: string) method, this method should be treated as method overloading. So Derived class should have both greet() and greet(name: string). Why we have error here? Thank you in advance!
Solution 1:[1]
Consider this simple example:
type EmptyGreet = () => void
type FullGreed = (arg: string) => void
let emptyGreed: EmptyGreet = () => { }
let fullGreed: FullGreed = (arg: string) => arg.toLowerCase()
emptyGreed = fullGreed // error
emptyGreed() // ok, but there is runtime error
fullGreed = emptyGreed // ok
fullGreed('hello') // ok, hello argument does not have any impact on business logic
As you might have noticed, it is unsafe to assign function with argument to the function without argument.
Same is here:
class Base {
greet() {
console.log("Hello, world!");
}
}
class Derived extends Base {
// Make this parameter required
greet(name: string) { // why we have error here?
console.log(`Hello, ${name.toUpperCase()}`);
}
}
const b: Base = new Derived();
b.greet(); // why it crashes here?
class Derived expects an argument for greet method and you are trying to call greet without such argument. This is why TS does not allow you to use explicit type Base for b const
this method should be treated as method overloading ...
This is not true. This is not how method overloading works in typescript.
class Foo {
foo(arg: string): string
foo(arg: number): number
foo(arg: any) {
return null as any
}
}
P.S. Please consider using keyword override (docs) if you want to override a method
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
