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
@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