簡體   English   中英

打字稿:使用裝飾器時的類型推斷

[英]Typescript: Type inference when using decorator

我想知道為什么當我在類的 Typescript 中使用裝飾器或注釋時。 編譯器無法推斷類的新類型。 如果我不使用裝飾器並使用舊的方式在 ES5 中做到這一點(即手動調用裝飾器),它顯然有效。

例如,這里有一個顯示問題的示例:

function decorate(Target: typeof Base): IExtendedBaseConstructor {
  return class extends Target implements IExtendedBase {
    public extendedtMethod(): number {
      return 3;
    }
  };
}

interface IBase {
  baseMethod(): number;
}

interface IExtendedBase extends Base {
  extendedtMethod(): number;
}

interface IExtendedBaseConstructor {
  new(): IExtendedBase;
}

@decorate
class Base implements IBase {
  public baseMethod(): number {
    return 5;
  }
}

const test = new Base();
test.baseMethod(); // OK
test.extendedtMethod(); // NOT OK, typescript think, Base is still Base but we decorated it.

使用較舊的方式,它可以工作:

class Base implements IBase {
  public baseMethod(): number {
    return 5;
  }
}

const ExtendedBase = decorate(Base);

const test = new ExtendedBase();
test.baseMethod(); // OK
test.extendedtMethod(); // OK

提前致謝。

現在這行不通。 github 上有一個懸而未決的問題,允許類裝飾器更改類的類型。

在實施之前,我建議您按照您提到的“舊方法”進行操作。

有一種方法可以使這項工作只需要一點額外的編碼。

對於任何類裝飾器,創建一個帶有其屬性和方法的接口。 以某種方式命名它,以便您可以輕松地將它與它所描述的裝飾器相關聯。 在你的情況下,它可能是:

interface IDecorate {
  extendedtMethod(): number;
}

對於任何需要此裝飾器的類,您只需創建一個與該類同名的接口,並讓它擴展所有必需的裝飾器接口:

@decorate
@anotherDecorator
class MyClass {
  // ...
}

interface MyClass extends IDecorate, IAnotherDecorator {}

現在,只需關閉 ESLint 或 TSLint 對空接口的警告,您就可以開始了。 裝飾器添加的任何方法或屬性現在都可以在裝飾類本身中使用。

暫無
暫無

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

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