0

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:

class Bar extends Foo<'test'> {
    public override test(): void {
        // todo
    }
}
3
  • what does I need to have an abstract method mean? There is no such thing as abstract method, there is an abstract class maybe? Commented Jul 14, 2022 at 16:32
  • Yes the class needs to be abstract as well. But of course there is such a thing as abstract methods. See typescriptlang.org/docs/handbook/classes.html#abstract-classes. Commented Jul 14, 2022 at 16:34
  • thanks didn't know there's such thing Commented Jul 14, 2022 at 16:36

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

If you don't insist on extends and override then you can do this with implements:

type Foo<T extends string> = {
    [_ in T]: () => void;
}

class Bar implements Foo<'test'> {
    public test() { /* todo */ }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.