【问题标题】:Typescript objects or classes: not possible to have additional properties when class implements interface?打字稿对象或类:当类实现接口时不可能有额外的属性?
【发布时间】:2020-04-27 06:09:51
【问题描述】:

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

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

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

【问题讨论】:

    标签: typescript class interface extension-methods


    【解决方案1】:

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

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

    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; } ,
    };
    

    【讨论】:

    • 是的,你说得对,对不起,我的意思是对象,我修改了我的问题,所以这准确地定义了我想要的对象,但是不可能将我的对象扩展到我的界面之上,对吧?
    • 您可以创建一个从另一个接口扩展的接口,然后说您的对象文字属于该扩展类型。我已经添加了一个例子。
    猜你喜欢
    • 2017-06-29
    • 2023-03-29
    • 1970-01-01
    • 2019-03-26
    • 2019-02-10
    • 2020-02-03
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多