簡體   English   中英

Typescript + ES6 代理

[英]Typescript + ES6 Proxy

ES6 Proxy.apply 方法提供了一種使用沒有“new”關鍵字的類的方法。

但是在 TypeScript 上,它給出了一個錯誤“'typeof ClassName'類型的值不可調用。你的意思是包括'new'嗎?”。

有什么方法可以防止 TypeScript 錯誤?

這是它的簡單示例;

class ClassName {
  constructor(anyThing?: any) {
    if (anyThing) {
      // Do something
    }
  }
}

// ES6 Proxy
const CustomName = new Proxy(ClassName, {
  apply: (Target, _thisArg, argumentsList) => {
    return new Target(...argumentsList);
  }
});

// Test ---------
new ClassName("test"); // return ClassName { }

// No error
new CustomName("test"); // return ClassName { }

// Javascript: no error
// TypeScript: error => Value of type 'typeof ClassName' is not callable. Did you mean to include 'new'?
CustomName("test"); // return ClassName { }

Typescript 無法理解您的應用 function 對 class 做了什么。 您將需要增加類型。

解決方案( 操場

class ClassName {
  constructor(anyThing?: any) {
    if (anyThing) {
      // Do something
    }
  }
}

// ES6 Proxy
const CustomName = new Proxy(ClassName, {
  apply: (Target, _thisArg, argumentsList) => {
    return new Target(...argumentsList);
  },
  get: () => { ... }, // Implement static method(s)
}) as typeof ClassName & (() => ClassName) & { staticMethod(): CustomName };

let instance: ClassName;

instance = new ClassName();
instance = new CustomName();
instance = CustomName();
instance = CustomName.staticMethod();

使用 Target 的 static 方法使代理可調用

class ClassName {
  constructor(anyThing?: any) {
    if (anyThing) {
      // Do something
    }
  }

  // Forge
  static forge (anyThing?: any) {
    return new ClassName(anyThing);
  }
}

// ES6 Proxy
const CustomName = new Proxy(ClassName, {
  apply: (Target, _thisArg, argumentsList) => {
    return new Target(...argumentsList);
  }
}) as typeof ClassName & typeof ClassName.forge;

let instance: ClassName;

instance = new ClassName();
instance = new CustomName();
instance = CustomName();

暫無
暫無

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

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