假设我有一个类:
class Foo<T extends string> { }
现在,我需要一个抽象方法,它的名称是T
的值。这可能吗?
用例看起来像这样:
class Bar extends Foo<'test'> {
public override test(): void {
// todo
}
}
差不多没什么(除了enum)永远不会从TypeScript的Type部分进入Javascript。这是一个编译时帮助您的开发经验。因此,做你要求的事是不可能的。
有一些高级特性,如映射类型等,它们允许您从现有的类型派生出新的类型。一个强大的特性是类似
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')
}
,但这些仅限于类型和其他。我建议您查看https://www.typescriptlang.org/docs/handbook/2/mapped-types.html
如果您不坚持使用extends
和override
,那么您可以使用implements
:
type Foo<T extends string> = {
[_ in T]: () => void;
}
class Bar implements Foo<'test'> {
public test() { /* todo */ }
}