簡體   English   中英

Typescript:在運行時從實例獲取類的通用方法

[英]Typescript: Generic way to obtain class at runtime from instance

考慮以下類,如何獲得基於“ this”引用的類的引用?

看到??? 下面。 我需要返回當前實例的類的東西。 子類this.type應該返回其類的TYPE屬性。 不是父類的。

謝謝,

家長班

export class TypedAction implements Action {
  static TYPE = [NONE];
  get type (): string {
    return ???; // non generic writing: return TypedAction.TYPE
  }
}

兒童班 (在其他班級中)

export class LoginRequestAction extends TypedAction {
  static TYPE = '[Auth] Login requested';
  constructor(public payload?: { username: string, password: string }){
    super();
  };
}

好的,找到解決方案。

export class TypedAction implements Action {
  static TYPE = '[NO TYPE]';
  get type (): string {
    return (<typeof TypedAction>this.constructor).TYPE; 
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM