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?
To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!
Arrays can be declared and initialized separately. let fruits: Array<string>; fruits = ['Apple', 'Orange', 'Banana']; let ids: Array<number>; ids = [23, 34, 100, 124, 44]; An array in TypeScript can contain elements of different data types using a generic array type syntax, as shown below.
Datatype: array_name:datatype[]=[]; Example string: users:string[]=[]; For array of objects: Objecttype: object_name:objecttype[]=[{}]; Example user: Users:user[]=[{}]; And if in some cases it's coming undefined in binding, make sure to initialize it on Oninit() .
How to declare and Initialize an array of objects with values. Objects are properties that contain keys and values, There is no type to represent the object in Typescript and angular. An array of strings can be declared and initialized with the below syntax. private arrays:Array<string> = ['one','two','three'];
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[]=[];
Class definitions should be like :
export class Environment {
cId:string;
cName:string;
constructor( id: string, name: string ) {
this.cId = id;
this.cName = name;
}
getMyFields(){
return this.cId + " " + this.cName;
}
}
var environments = new Environment('a','b');
console.log(environments.getMyFields()); // will print a b
Source: https://www.typescriptlang.org/docs/handbook/classes.html
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With