【问题标题】:Any class that extends class type任何扩展类类型的类
【发布时间】:2019-05-15 03:03:44
【问题描述】:

我如何声明一个类型为typeof B任何扩展B 的类?我创建了一个类型,它接受扩展 Component 类的类数组,但这不适用于 TSC 3.(1.4|2.1)。

export class Component<S> {}

export type ComponentClass = new () => Component<{ message: string }>;

export interface ComponentFlags<S> {
	imports?: (typeof Component | new () => Component<any>)[]
}

export class Message extends Component<State> {}

export class Dialog extends Component<State> {
	constructor(el: HTMLDivElement) {
		super({
			imports: [Message]
		});
	}
}

这会在编译时引发错误。

type 'typeof Message' is not assignable to type 'typeof Component'.

【问题讨论】:

  • 似乎工作正常:typescriptlang.org/play/…
  • 听起来更好。
  • 代码在 TypeScript 3.2.2 上似乎没问题。没有 TypeScript 错误。
  • 那里。刚刚公开了一些我正在使用的代码。现在应该更有意义了。
  • @lurker 这是我正在使用的代码,但我删除了与问题无关的内容——我不希望任何人看到。

标签: typescript


【解决方案1】:

使用这个:

const a = <T extends new(...args: any) => B> (p: T|B) => p;

对于您的情况:

export type NewComponnent = new (...args: any[]) => Component<any>;

export interface ComponentFlags<S> {
    imports?: (components: NewComponent[]) => void;
    // OR
    // imports?: (...components: NewComponent[]) => void;
}

【讨论】:

  • 不过,我不想将它作为泛型类型传递。
  • 不要认为那是对的。 Array&lt;Component&lt;any&gt;&gt; 表示 Component 实例的数组。
  • @WillHoskings 已修复
  • 谢谢。 new () =&gt; Component&lt;any&gt; 与带参数的构造函数不兼容是有道理的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多