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
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.
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.
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.
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.
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 { }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With