Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring protected attribute in interface

Tags:

typescript

Is it possible to declare protected attributes in TypeScript interfaces?

For example:

interface IsDrawable {
  // protected // <- seems to be unsupported
  cssClass: string;
}

class SomeClass implements IsDrawable {
  protected // <- errors
  cssClass: string;
}

SomeClass errors with `Class 'SomeClass' incorrectly implements interface 'IsDrawable'. Property 'cssClass' is protected in type 'SomeClass' but public in type 'IsDrawable'.

like image 200
AJP Avatar asked Oct 01 '15 13:10

AJP


2 Answers

Try to understand sense of Interface in any languages.

Since Interface is schema that anyone can use to access some class features, its fields can not be private or protected

like image 82
Oleh Dokuka Avatar answered Oct 13 '22 07:10

Oleh Dokuka


An interface is a contract meaning you are telling entities outside of yourself what you can do and what you have, by making them protected you are breaking that contract.

That being said, you want to force the implementation of something scoped as protected, you can use abstract classes to fit that need. They are new as of version 1.6 https://github.com/Microsoft/TypeScript/issues/3578

Update

abstract cannot be applied to properties, so in order to make this work, cssClass would need to be a method which would return the string.

like image 32
Brocco Avatar answered Oct 13 '22 07:10

Brocco