[英]TypeScript type checking on type rather than instance (part 2)
第一部分提出了一個問題-“ TypeScript是否可以確保參數是給定類型或其派生類型,而不是類型或其派生實例?”
第一部分的解決方案是使用typeof
關鍵字
例
function giveMeAType(type: typeof Foo): void {
}
或與泛型
function giveMeAType<T extends typeof Foo>(type: T): void {
}
擴展此解決方案,將構造函數引入派生類型時,我遇到了一個新問題
class Mangler<T> {
protected constructor(
public readonly item: T) {
}
public static getManglers(mangler: typeof Mangler): typeof Mangler[] {
var whatever = [];
return whatever;
}
}
class StringMangler extends Mangler<string> {
// No constructor override here...
}
class NumberMangler extends Mangler<number> {
// But in this case, I need one...
private constructor(
public readonly item: number) {
super(item);
}
}
// This one works while StringMangler does not override the constructor.
Mangler.getManglers(StringMangler);
// But when I override the constructor, it doesn't work.
Mangler.getManglers(NumberMangler);
然后,如何使用構造函數重寫維護類型檢查?
PS我希望派生類型能夠具有私有或受保護的構造函數!
更新1
要詳細說明Nitzan Tomer的答案,我可以使構造函數protected
,並且錯誤消失,但是我不能使構造函數具有多態性。
class NumberMangler extends Mangler<number> {
// This polymorphic constructor doesn't work.
public constructor(
public readonly item: number,
public readonly name: string) {
super(item);
}
}
如果使NumberMangler.constructor
受保護,則錯誤消失:
class NumberMangler extends Mangler<number> {
protected constructor(
public readonly item: number) {
super(item);
}
}
這應該工作:
class NumberMangler extends Mangler<number> {
protected constructor(item: number);
protected constructor(item: number, name: string);
protected constructor(
public readonly item: number,
public readonly name?: string) {
super(item);
}
}
您實際上不需要非實現簽名,但是我認為它使可讀性更高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.