Created
August 28, 2021 20:01
-
-
Save evantahler/a8d60c68f609f93d1d3457d3aa57a18f to your computer and use it in GitHub Desktop.
Inheriting class method augment types in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class Greeter { | |
abstract greet(who: string, message: string): void; | |
} | |
class ClassyGreeter extends Greeter { | |
greet(who, message) { | |
console.log(`Salutations, ${who}. ${message}`); | |
} | |
} | |
const classyGreeterInstance = new ClassyGreeter(); | |
classyGreeterInstance.greet("Mr Bingley", "Is it not a fine day?"); // OK, inputs are strings | |
classyGreeterInstance.greet(1234, false); // Should Throw maybe |
I think you're expecting a feature of abstract classes that does not exist . From my understanding abstract classes can only insure methods are implemented to desired spec, however the child must insure new instances are follow the desired implementation of the parent. I'm sure they will come up with several use cases for why its done this way but I think you may need open an issue with them you may have the next great feature on your hands.
By default 'any' types are applied to your inputs which are compatible with 'string' types.
However you would throw a ts error if you tried
greet(who:number, message:boolean) {. . .}
which I'm sure you have experienced
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Consider the above abstract class and implementation class. The
greet()
method in the abstract class strongly types the two arguments to both be strings. However, the implementing class,ClassyGreeter
doesn't know the types of the two arguments.How can we inform
ClassyGreeter#greet
of the types of its arguments from the abstract class? The goal is to get a type error on line 12(
classyGreeterInstance.greet(1234, false)
) without needing to add types to ClassyGreeter and load them in some way from Greeter.