Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript error : Property defined as private on type Class is defined as public on type Interface

Tags:

typescript

I just started a new project in TypeScript 0.9.5 and the following code is throwing an error :

Class Service declared IService but does not implement it. Property 'getUserInfo' defined as private on type Service is defined as public on type IService

 module App.Interfaces {

     export interface IService {
        getUserInfo(): void;

    }   
}

module App.Services {

    export class Service implements App.Interfaces.IService {

        private getUserInfo(): void { }

    }   
}

For as long as I've used TypeScript I know that interfaces cannot have access modifiers! What gives?

Typescript playground example

like image 357
parliament Avatar asked Jan 25 '14 21:01

parliament


People also ask

Can we define private method in interface TypeScript?

How to define a private property when implementing an interface in TypeScript? To define a private property when implementing an interface in TypeScript, we can add private properties into the class that implements the interface. to add the name private variable into the ModuleMenuItem class.

How do you define a function in interface TypeScript?

TypeScript Interface can be used to define a function type by ensuring a function signature. We use the optional property using a question mark before the property name colon. This optional property indicates that objects belonging to the Interface may or may not have to define these properties.

What is protected in TypeScript?

protected implies that the method or property is accessible only internally within the class or any class that extends it but not externally. Finally, readonly will cause the TypeScript compiler to throw an error if the value of the property is changed after its initial assignment in the class constructor.

How do I create an instance of an interface in TypeScript?

To create an object based on an interface, declare the object's type to be the interface, e.g. const obj1: Employee = {} . The object has to conform to the property names and the type of the values in the interface, otherwise the type checker throws an error.


1 Answers

You can't have the private access modifier on the getUserInfo function on the Service class as it's declared on the interface IService.

If the class is a IService, it needs to have all of the functions/properties of the interface declared publicly.

module App.Services {

    export class Service implements App.Interfaces.IService {

        /* private <= remove */ getUserInfo(): void { }

    }   
}
like image 200
WiredPrairie Avatar answered Oct 13 '22 07:10

WiredPrairie