我想創建一個可以使用new關鍵字呼叫的函式。但是,我的實作都不起作用,Typescript 不斷向我顯示錯誤。
下面是我的代碼。你也可以在Typescript Playground上看到它
type Account = {
username: string
password: string
}
type AccountConstructor = {
new (username: string, password: string): Account
(username: string, password: string): Account
}
// const Account: AccountConstructor = function (username: string, password: string) {
// return {username, password}
// }
// Type '(username: string, password: string) => { username: string; password: string; }' is not assignable to type 'AccountConstructor'.
// Type '(username: string, password: string) => { username: string; password: string; }' provides no match for the signature 'new (username: string, password: string): Account'.
const Account: AccountConstructor = function(username: string, password: string) {
return {
username,
password
}
}
// Type 'typeof Account' is not assignable to type 'AccountConstructor'.
// Type 'typeof Account' provides no match for the signature '(username: string, password: string): Account'.
const Account: AccountConstructor = class {
constructor(public username: string, public password: string) {}
}
new Account('username', 'password')
如何正確實作構造簽名以便可以使用new關鍵字呼叫函式?
uj5u.com熱心網友回復:
在 Typescript 代碼中,您應該撰寫類,而不是建構式;class建構式是在添加語法之前在 Javascript 中實作“類”的舊方法。此模式仍可用于較舊的庫,或出于兼容性目的編譯為 ES5 或更早版本的庫。(如果您需要這種兼容性,請將您的目標設定為 ES5,您的 Typescriptclass宣告將在您編譯時自動轉換。)
建構式簽名主要.d.ts用于在檔案中為不是用 Typescript 撰寫的庫定義型別時使用。但是,您也可以使用它們來傳遞類,如下所示:
type Foo = {x: string}
type FooConstructor = new (x: string) => Foo
class FooClass {
constructor(public x: string) {}
}
const fooConstructor: FooConstructor = FooClass;
游樂場鏈接
這與您使用類的示例之間的區別在于,您的介面需要構造簽名和呼叫簽名,但類沒有呼叫簽名。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515582.html
標籤:打字稿
上一篇:當T是嵌套函式的回傳型別時,如何讓Typescript知道GenericT的型別?
下一篇:貓鼬虛擬填充問題(缺少填充欄位)
