TypeScript是包含類型的ES6 Javascript的超集。類可以使用class
關鍵字聲明,並使用new
關鍵字實例化,類似於它們在Java中的使用方式。在TypeScript中,可以使用沒有「新」關鍵字的類嗎?
我想知道在TypeScript中是否有任何用例可以實例化類,而不使用new
關鍵字。
我之所以這樣問是因爲我不知道如果,假設我有一個名爲Bob
類,我可以假設的Bob
任何實例的實例與new Bob()
。
TypeScript是包含類型的ES6 Javascript的超集。類可以使用class
關鍵字聲明,並使用new
關鍵字實例化,類似於它們在Java中的使用方式。在TypeScript中,可以使用沒有「新」關鍵字的類嗎?
我想知道在TypeScript中是否有任何用例可以實例化類,而不使用new
關鍵字。
我之所以這樣問是因爲我不知道如果,假設我有一個名爲Bob
類,我可以假設的Bob
任何實例的實例與new Bob()
。
對這個打字稿保障在默認情況下,因此,如果你這樣做:
class A {}
let a = A();
你會得到一個錯誤:
Value of type
typeof A
is not callable. Did you mean to include 'new'?
但是有可以不使用創建一些對象new
關鍵字,基本上都是本地類型。
如果你看一下lib.d.ts你可以看到不同的構造函數的簽名,例如:
interface StringConstructor {
new (value?: any): String;
(value?: any): string;
...
}
interface ArrayConstructor {
new (arrayLength?: number): any[];
new <T>(arrayLength: number): T[];
new <T>(...items: T[]): T[];
(arrayLength?: number): any[];
<T>(arrayLength: number): T[];
<T>(...items: T[]): T[];
...
}
,你可以看看有沒有關鍵字new
總是相同的ctors。
如果你願意,你當然可以模仿這種行爲。
重要的是要知道,儘管打字稿檢查以確保不會發生這種情況,但javascript不檢查,所以如果有人寫js代碼來使用你的代碼,他可能會忘記使用new
,所以這個情況仍然是可能的。
很容易檢測到這是否發生在運行時,然後按照您認爲合適的方式處理它(引發錯誤,通過使用new
返回實例並記錄它來修復它)。
下面是談關於它的帖子:Creating instances without new(純JS),但TL;博士是:
class A {
constructor() {
if (!(this instanceof A)) {
// throw new Error("A was instantiated without using the 'new' keyword");
// console.log("A was instantiated without using the 'new' keyword");
return new A();
}
}
}
let a1 = new A(); // A {}
let a2 = (A as any)(); // A {}
聽起來你說,簡短的回答是「是」 。 –
確實,簡短的回答是:是的,可以在不使用'new'的情況下調用ctor(但在這種情況下,您將不會有實例) –