0

I am trying to make a simple form with typescript. I want to create an array of 'username password' each time I create a user.

export class Form{
username : string;
password : string;
isChecked : boolean;
arr: string[] = new Array();

constructor(){
    this.isChecked = false;
}

signup(){

this.arr.push(this.username);
console.log(this.arr);

}

submit(){
var res = document.getElementById('check');
res.innerText = String(this.isChecked);
}
}

This code works but only with username when I check on the console but I want something that gives me arr[0] --> username, password and not only the username for example. I know it is something with the declaration of arr but I try other ways to declare it and I always get stuck.

3
  • Are you trying to describe an array of a tuple type e.g. [string, string][]? See typescriptlang.org/play/… Commented Feb 13, 2018 at 16:40
  • do you actually want an 2D-array (array of array) ? like [["username","password"]] ? or maybe an array of object [{username:"foo",password:"bar"}] ? Commented Feb 13, 2018 at 16:40
  • please add a json example of the array. :) it would help us know what you want to store in it. Commented Feb 13, 2018 at 16:57

1 Answer 1

1

You could create a class object for User and use that e.g.

class User {
    username: string;
    password: string;
    constructor(username: string, password: string) {
        this.username = username;
        this.password = password;
    }
}

and your array implementation would look like this

  let arr: User[] = new Array();
  arr.push({
      username: "Billy",
      password: "hunter42"
  });
  arr.push(new User("Billy", "hunter42"));

You can use both versions, but since you are using typescript you might aswell use the second version by calling the constructor with new User().

Sign up to request clarification or add additional context in comments.

1 Comment

That's what i was looking for and the solution with a class User is also interesting thanks a lot!

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.