简体   繁体   English

基于泛型类型的打字稿方法名称

[英]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 .现在,我需要一个抽象方法,其名称是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.几乎没有任何东西(除了枚举)能从 TypeScript 的 Type 部分变成 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我建议您查看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 :如果您不坚持extendsoverride ,那么您可以使用implements此操作:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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