简体   繁体   中英

Weird Behaviour of typescript when declaring variable using interface

I am using the interface to define a type of variable and initializing that variable with a class that has some additional properties than the interface. please refer to the code below:

interface User {
  name: string;
  id: number;
}

class UserAccount {
  name: string;
  id: number;
  username: string

  constructor(name: string, id: number, username: string) {
    this.name = name;
    this.id = id;
    this.username = username;
  }
}

const user: User = new UserAccount("Suraj", 1, "srs");
// user.username
// I will not be able to access username in above line but when I console it, it will show the value assigned by the class constructor
console.log(user)
// output will be **UserAccount { name: 'Murphy', id: 1, username: 'srs' }**

My question is:

  1. Why we are using Interface when we are initializing variables with the class?
  2. And if we are using this then why it is not an error in the typescript when compiling?
  3. And last if we are able to assign it (UserAccount { name: 'Murphy', id: 1, username: 'srs' }) then why can't we access user.username ?

(Typing from phone, can add details later)

For starters you are not using the interface. You defined a class and an interface that are completely unrelated and only have similar names.

To actually use the interface you'd have to do something like:

class UserAccount implements User { … }

Now answering your questions:

  1. There many reasons one would create interfaces. For instance you could share the interface with a different parte of the code letting it know what a UserAccount looks like without creating a dependency on the class itself. Another user can be to define multiple interfaces such as “SoundPlayer” and “GraphicsPlayer”, then have a class implement one or both. Those classes could represent a music player by implementing “SoundPlayer” or a multimedia player by implementing both. This also ensures that classes with similar functions “look the same”.

  2. Not sure what you're asking but I feel like you were expecting some sort of error that won't occur since you're not actually implementing the interface.

  3. You can't access user.username because it is part of the class UserAccount and not part of the interface.

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