Skip to content

Instantly share code, notes, and snippets.

@evantahler
Created August 28, 2021 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evantahler/a8d60c68f609f93d1d3457d3aa57a18f to your computer and use it in GitHub Desktop.
Save evantahler/a8d60c68f609f93d1d3457d3aa57a18f to your computer and use it in GitHub Desktop.
Inheriting class method augment types in Typescript
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
@evantahler
Copy link
Author

evantahler commented Aug 28, 2021

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.

Screen Shot 2021-08-28 at 1 00 27 PM

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.

@mpareja-godaddy
Copy link

mpareja-godaddy commented Aug 30, 2021

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