简体   繁体   中英

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:

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

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

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 */ }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM