Why does this happen in Angular2 and Typescript?
export class Environment {
constructor(
id: string,
name: string
) { }
}
environments = new Environment('a','b');
app/environments/environment-form.component.ts(16,19): error TS2346: Supplied parameters do not match any signature of call target.
How on do I initialize an array?
This question is related to
typescript
angular
I don't fully understand what you really mean by initializing an array?
Here's an example:
class Environment {
// you can declare private, public and protected variables in constructor signature
constructor(
private id: string,
private name: string
) {
alert( this.id );
}
}
let environments = new Environment('a','b');
// creating and initializing array of Environment objects
let envArr: Array<Environment> = [
new Environment('c','v'),
new Environment('c','v'),
new Environment('g','g'),
new Environment('3','e')
];
Try it here : https://www.typescriptlang.org/play/index.html
In order to make more concise you can declare constructor parameters as public
which automatically create properties with same names and these properties are available via this
:
export class Environment {
constructor(public id:number, public name:string) {}
getProperties() {
return `${this.id} : ${this.name}`;
}
}
let serverEnv = new Environment(80, 'port');
console.log(serverEnv);
---result---
// Environment { id: 80, name: 'port' }
You can use this construct:
export class AppComponent {
title:string;
myHero:string;
heroes: any[];
constructor() {
this.title = 'Tour of Heros';
this.heroes=['Windstorm','Bombasto','Magneta','Tornado']
this.myHero = this.heroes[0];
}
}
you can create and initialize array of any object like this.
hero:Hero[]=[];
hi @JackSlayer94 please find the below example to understand how to make an array of size 5.
class Hero {_x000D_
name: string;_x000D_
constructor(text: string) {_x000D_
this.name = text;_x000D_
}_x000D_
_x000D_
display() {_x000D_
return "Hello, " + this.name;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
let heros:Hero[] = new Array(5);_x000D_
for (let i = 0; i < 5; i++){_x000D_
heros[i] = new Hero("Name: " + i);_x000D_
}_x000D_
_x000D_
for (let i = 0; i < 5; i++){_x000D_
console.log(heros[i].display());_x000D_
}
_x000D_
Source: Stackoverflow.com