Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript method name based on generic type

Suppose I have a class like:

class Foo<T extends string> { }

Now, I need to have an abstract method, the name of which is the value of T. Is that possible?

The use-case would look something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Bar extends Foo<'test'> {
    public override test(): void {
        // todo
    }
}

>Solution :

Pretty much nothing (with the exception of enums) will ever make it from the Type part of TypeScript into Javascript. It’s a compile time aid for your development experience. Thus it is impossible to do what you ask.

There are advanced features like mapped types and the like, and they allow you to do amazing things deriving new types from existing ones. A powerful feature is something like

type A = {
  ho: boolean;
  hi: number;
  hu: string;
}

type B<T> = {
 [key in keyof T]: () => void
};

// Property 'hu' is missing in type '{ ho: () => void; hi: () => void; }' 
// but required in type 'B<A>'
const obj: B<A> = { 
  ho: () => console.log('ho'),
  hi: () => console.log('hi')
}

but these are limited to types and otherwise. I recommend you check out https://www.typescriptlang.org/docs/handbook/2/mapped-types.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading