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
}
}
CodePudding user response:
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
CodePudding user response:
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 */ }
}