Search code examples
typescriptclassinterfaceextension-methods

Typescript objects or classes: not possible to have additional properties when class implements interface?


I was wondering why its not possible to implement additional properties or functions inside a typescript class when this class implements an interface... it says: ..."Object literal may only specify known properties and "FirstName" does not exist in type persInterface".. I think in java its also possible to implement other props or functions, the implementas interface is just a mandatory subset of the class and not a restriction.. is that behaviour normal in Typescript?

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

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

Solution

  • You talk about classes implementing interfaces, but then your example code doesn't do that, it just has an object literal. With that object literal, you've defined that it will be exactly a persInterface, which is why you get an error when trying to add a property that's not part of persInterface.

    If you do actually try to have a class which implements an interface then you can do what you want, without any type errors (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');
    

    If you're working with literals, then you'd want to create an interface that extends from the base interface and specify what the extra properties are:

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