【发布时间】:2022-01-25 02:20:33
【问题描述】:
我正在使用接口来定义一种变量,并使用一个具有比接口更多属性的类来初始化该变量。 请参考以下代码:
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' }**
我的问题是:
- 为什么在使用类初始化变量时使用接口?
- 如果我们使用它,那么为什么编译时打字稿没有错误?
- 最后,如果我们能够分配它 (UserAccount { name: 'Murphy', id: 1, username: 'srs' }) 那么为什么我们不能访问 user .用户名?
【问题讨论】:
标签: javascript typescript class oop interface