Classes | Typescript
Inheritance#
Calling super()#
Public, private, and protected modifiers#
Public by default#
Private#
ECMAScript Private Fields#
TypeScript’s private#
When comparing types that have private and protected members, we treat these types differently. For two types to be considered compatible, if one of them has a private member, then the other must have a private member that originated in the same declaration. The same applies to protected members.
Protected#
The protected modifier acts much like the private modifier with the exception that members declared protected can also be accessed within deriving classes.
A constructor may also be marked protected. This means that the class cannot be instantiated outside of its containing class, but can be extended.
Readonly modifier#
Readonly properties must be initialized at their declaration or in the constructor.
Parameter properties#
Parameter properties let you create and initialize a member in one place.
Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or readonly, or both.
Accessors#
get / set
- Accessors require you to set the compiler to output ECMAScript 5 or higher. Downleveling to ECMAScript 3 is not supported.
- accessors with a get and no set are automatically inferred to be readonly. This is helpful when generating a .d.ts file from your code, because users of your property can see that they can’t change it.
Static Properties#
Abstract Classes#
Abstract classes are base classes from which other classes may be derived. They may not be instantiated directly.
Unlike an interface, an abstract class may contain implementation details for its members.
Advanced Techniques#
Constructor functions#
When you declare a class in TypeScript, you are actually creating multiple declarations at the same time.
- type of the instance of the class
- constructor function