使用接口声明变量时typescript的怪异行为



我正在使用接口定义一种类型的变量,并用一个比接口具有一些附加属性的类初始化该变量。请参考以下代码:

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' }**

我的问题是:

  1. 当我们用类初始化变量时,为什么要使用Interface
  2. 如果我们正在使用它,那么为什么在编译时它不是typescript中的错误呢
  3. 最后,如果我们能够分配它(UserAccount{name:'Murphy',id:1,用户名:'srs'}(,那么为什么我们不能访问用户。用户名

(通过电话打字,稍后可以添加详细信息(

对于初学者来说,您没有使用该界面。您定义了一个类和一个接口,它们完全不相关,只有相似的名称。

要真正使用该界面,您必须执行以下操作:

类UserAccount实现User{…}

现在回答您的问题:

  1. 创建接口的原因有很多。例如,您可以与代码的另一部分共享接口,让它知道UserAccount是什么样子的,而无需创建对类本身的依赖关系。另一个用户可以定义多个接口,如"SoundPlayer"one_answers"GraphicsPlayer",然后让一个类实现其中一个或两个。这些类可以通过实现"SoundPlayer"来表示音乐播放器,也可以通过实现两者来表示多媒体播放器。这也确保了具有类似函数的类"看起来相同"。

  2. 不确定你在问什么,但我觉得你在期待某种不会发生的错误,因为你实际上并没有实现接口。

  3. 您无法访问user.username,因为它是类UserAccount的一部分,而不是接口的一部分。

最新更新