簡體   English   中英

打字稿中的new()是什么意思?

[英]What does new?() mean in typescript?

我在打字稿游樂場有以下代碼片段:

interface IFoo {
    new?():string;

}

class Foo implements IFoo {
    new() {
     return 'sss'; 
    }

}

我必須輸入“?” 在接口方法new中,否則將顯示編譯錯誤。 我不知道為什么。

更新:原始問題不是使用new的好方法,因此我發布了一種使用上述new()的更現實和實際的方法:

interface IUser {
  id: number;
  name: string;
}

interface UserConstructable {
  new (id: number, name: string, ...keys: any[]): IUser;
}

class User implements IUser {
  constructor(public id: number, public name: string) {

  }
}

class Employee implements IUser {
  constructor(public id: number, public name: string, 
    private manager: string) {

  }
}


class UserFactory {
   private static _idx: number = 0;
   static makeUser(n: UserConstructable): IUser {
      let newId = UserFactory._idx++;

      return new n(newId, 'user-' + newId, 'manager-' + newId);
   } 
}

console.log(UserFactory.makeUser(User));
console.log(UserFactory.makeUser(User));
console.log(UserFactory.makeUser(Employee));

讓我們將其分為幾部分...我知道您已經知道其中一些內容,但是我正在嘗試完成。

1..2.3..4
new?():string;
  1. 在此特定上下文中, new不是關鍵字,它只是方法名稱...由於此列表中的下一項...

  2. ? 使它成為可選的(即,您可以實現接口而無需實現此方法)。

  3. ()表示new是一種方法。

  4. 返回類型是一個字符串

class Foo implements IFoo {
    new() {
        return 'sss'; 
    }
}

class Bar implements IFoo {
    // Because new is optional, you don't have to implement it
}

如果省略了? ,那么您使用new作為關鍵字-但TypeScript將示例中的代碼解釋為一種簡單方法。

不過,總的來說,我會避免使用一個稱為保留字的名稱來命名一個成員。

在javascript中,函數是對象,因此打字稿接口也應該能夠匹配函數。 這就是為什么我們得到那些奇怪的界面的原因。

interface SomeFunc {
  (key: string): boolean;
  (key: number): boolean;
}

該接口將僅與接受字符串或數字並返回布爾值的函數匹配。

現在考慮構造函數(例如ES5-中的類)的情況。

function MyClass() {
  this.prop = value;
}
let myClass = new MyClass;

我們需要一種創建與MyClass函數簽名匹配的接口的方法。 這是我們在接口中獲得new功能的地方。

interface IFoo {
  new (key: string): {key:string};
}

function someFunction(key: string) { // doesn't match IFoo
  return {key};
}

var someObject = { // still doesn't match IFoo
  new(key: string) { 
    return {key};
  },
};

function MyClass(key: string) { // matches IFoo! must be called like `new MyClass()`
  this.key = key;
}

因此可以說new函數的簽名必須與類構造函數的簽名匹配。

interface IFoo {
  new(key: string): {};
}
class Foo implements IFoo { // works ok
  constructor(key: string) { // you can't return anything
  }
}

我認為您想做的是這樣的:

interface IFoo {
  new: () => string;
}

IFoo應該具有一個名為new的屬性,該屬性是一個返回字符串的函數。

暫無
暫無

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

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