简体   繁体   中英

Typescript compilation error with Arrays

There are two typescript files:

  • a module that implements the class Client

export class Client {
  • a main file that imports the module and creates an array of clients

import c = module("client")
//...
class Server {
    constructor() {
        this.clients = new c.Client[];

Compiling the code seems to work fine. But when I try to run the generated javascript with nodejs, it complains that there is a syntax error:

this.clients = new ();

On the client side there's typescript code, too. But instead of modules, I'm using declaration paths and the --out compiler flag to compile everything into one .js file. Arrays in the client-side code are created without problems. In the javascript there's

this.arr = new Array();

So obviously the compiler just forgot to add specify that an Array is created with new() . I fixed the error manually by just inserting the missing part. But after a small change to the code and a new compilation, the same problem appeared again. I'm using typescript version 0.8.3 and installed via npm. What can I do ?

I assume your class Server defines clients to be an array of c.Client objects so it actually looks like this:

class Server {
    clients: c.Client[];
    constructor() {
        this.clients = new c.Client[];
    }
}

I'm not sure why this code compiled at all because it's actually a syntax error. It doesn't compile for me.

You mixed up two different ways to declare an array: new Array() and [] . Just change your line to this and you should be good to go:

this.clients = [];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM