2016-08-03 53 views
1

TypeScript是包含类型的ES6 Javascript的超集。类可以使用class关键字声明,并使用new关键字实例化,类似于它们在Java中的使用方式。在TypeScript中,可以使用没有“新”关键字的类吗?

我想知道在TypeScript中是否有任何用例可以实例化类,而不使用new关键字。

我之所以这样问是因为我不知道如果,假设我有一个名为Bob类,我可以假设的Bob任何实例的实例与new Bob()

回答

4

对这个打字稿保障在默认情况下,因此,如果你这样做:

class A {} 
let a = A(); 

你会得到一个错误:

Value of type typeof A is not callable. Did you mean to include 'new'?

但是有可以不使用创建一些对象new关键字,基本上都是本地类型。
如果你看一下lib.d.ts你可以看到不同的构造函数的签名,例如:

StringConstructor

interface StringConstructor { 
    new (value?: any): String; 
    (value?: any): string; 
    ... 
} 

ArrayConstructor

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 {} 

code in playground

+2

听起来你说,简短的回答是“是” 。 –

+0

确实,简短的回答是:是的,可以在不使用'new'的情况下调用ctor(但在这种情况下,您将不会有实例) –

相关问题