I'd like to declare a private class, only to be used inside the file it was defined, is this possible? For example declared inside another class:
export class MyParentClass { class MyChildClass { } }
or inside the same file:
export class MyPublicClass { //Usage of MyPrivateClass } class MyPrivateClass { }
To create nested classes in TypeScript, we can create a static class property in our class. class Foo { static Bar = class {}; } const foo = new Foo(); const bar = new Foo. Bar(); to create the Foo class that has the static Bar property which is set to a class expression.
In TypeScript there are two ways to do this. The first option is to cast the object to any . The problem with this option is that you loose type safety and intellisense autocompletion. The second option is the intentional escape hatch.
Is it possible to define nested/inner class in typescript? Yes, it is. Go to chapter 3 or 4 if you want to know only nested/inner class.
TypeScript Private Properties Using TypeScript, we can add private functionality into our classes. What are private properties or methods? A private property of method can only be accessed or called from the class instance itself.
module MyModule { export class MyPublicClass { private myPrivateClass: PrivateClass; constructor() { this.myPrivateClass = new PrivateClass; } public test() { this.myPrivateClass.test(); } } class PrivateClass { public test() { console.log('it works'); } } }
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