117

I have the following classes in TypeScript:

class bar {
    length: number;
}

class foo {
    bars: bar[] = new Array();
}

And then I have:

var ham = new foo();
ham.bars = [
    new bar() {          // <-- compiler says Expected "]" and Expected ";"
        length = 1
    }
];

Is there a way to do that in TypeScript?

UPDATE

I came up with another solution by having a set method to return itself:

class bar {
    length: number;

    private ht: number;
    height(h: number): bar {
        this.ht = h; return this;
    }

    constructor(len: number) {
        this.length = len;
    }
}

class foo {
    bars: bar[] = new Array();
    setBars(items: bar[]) {
        this.bars = items;
        return this;
    }
}

so you can initialize it as below:

var ham = new foo();
ham.setBars(
    [
        new bar(1).height(2),
        new bar(3)
    ]);
1
  • It would be really useful to have object initializers in TypeScript similar to C#. [ {length: 1} ] is not instance of bar but if supported, new bar() { length = 1 } would be instance of bar. Maybe we should make a feature suggestion for this? Commented Aug 19, 2013 at 18:30

5 Answers 5

89

There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.

Option 1:

class bar {
    // Makes a public field called 'length'
    constructor(public length: number) { }
}

bars = [ new bar(1) ];

Option 2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];
Sign up to request clarification or add additional context in comments.

3 Comments

to make things clearer and typesafe : bars:bar[]=[{length:1}]
Is there any way to do this without defining classes?
The question is about how to initialize an array in a class. There isn't a way to initialize an array in a class without using classes.
29

If you really want to have named parameters plus have your objects be instances of your class, you can do the following:

class bar {
    constructor (options?: {length: number; height: number;}) {
        if (options) {
            this.length = options.length;
            this.height = options.height;
        }
    }
    length: number;
    height: number;
}

class foo {
    bars: bar[] = new Array();
}

var ham = new foo();
ham.bars = [
    new bar({length: 4, height: 2}),
    new bar({length: 1, height: 3})
];

Also here's the related item on typescript issue tracker.

1 Comment

+1 for issue link. You can also make initializer values optional: options? : {length?: number; height?: number;}
15

A simple solution could be:

interface bar {
    length: number;
}

let bars: bar[];
bars = [];

Comments

4

If you would like to 'add' additional items to a page, you may want to create an array of maps. This is how I created an array of maps and then added results to it:

import { Product } from '../models/product';

products: Array<Product>;          // Initialize the array.

[...]

let i = 0;
this.service.products( i , (result) => {

    if ( i == 0 ) {
        // Create the first element of the array.
        this.products = Array(result);
    } else { 
        // Add to the array of maps.
        this.products.push(result);
    }

});

Where product.ts look like...

export class Product {
    id: number;
    [...]
}

1 Comment

If you initialise the Array like this: products: Array<Product> = []; you don't have to do the if clause.
3

An other solution:

interface bar {
    length: number;
}

bars = [{
  length: 1
} as bar];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.