首页 > 解决方案 > 打字稿对象或类:当类实现接口时不可能有额外的属性?

问题描述

我想知道为什么当这个类实现一个接口时,它不可能在打字稿类中实现额外的属性或函数......它说:...... "Object literal may only specify known properties and "FirstName" does not exist in type persInterface"..我认为在java中它也可以实现其他道具或函数,implementas接口只是该类的强制子集,而不是限制..这种行为在 Typescript 中是否正常?

interface persInterface {
         lastName: String,
         sayHello: () => number
     }

 var person: persInterface = { 
    FirstName:"Tom", 
    lastName:"Hanks", 
    sayHello: ()=>{ return 10} ,
 };

标签: typescriptclassinterfaceextension-methods

解决方案


您谈论实现接口的类,但是您的示例代码没有这样做,它只有一个对象文字。使用该对象字面量,您已将其定义为完全是 persInterface,这就是为什么在尝试添加不属于 persInterface 的属性时会出现错误的原因。

如果您确实尝试拥有一个实现接口的类,那么您可以做您想做的事,而不会出现任何类型错误(操场链接):

interface persInterface {
  lastName: string,
  sayHello: () => number
}

class Person implements persInterface {
  firstName: string;
  lastName: string;
  constructor(firstName: string, lastName: string) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  sayHello(): number {
    return 10;
  }
}


const person = new Person('tom', 'hanks');

如果您正在使用文字,那么您需要创建一个从基本接口扩展的接口并指定额外的属性是什么:

interface persInterface {
  lastName: string,
  sayHello: () => number
}

interface persPlusPlus extends persInterface {
  lastName: string
}

const person: persPlusPlus = { 
  firstName:"Tom", 
  lastName:"Hanks", 
  sayHello: ()=> { return 10; } ,
};

推荐阅读