From fc79ca2150d8bae527ded9bcaa874d5d9905f8d3 Mon Sep 17 00:00:00 2001 From: Jasmeet Singh Date: Wed, 3 Jul 2019 19:34:50 +0530 Subject: [PATCH] Add TypeScript's modifiers guide. (#28081) * Add TypeScript's modifiers guide. * fix/suggested-changes --- guide/english/typescript/modifiers/index.md | 87 +++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 guide/english/typescript/modifiers/index.md diff --git a/guide/english/typescript/modifiers/index.md b/guide/english/typescript/modifiers/index.md new file mode 100644 index 0000000000..67dce3af64 --- /dev/null +++ b/guide/english/typescript/modifiers/index.md @@ -0,0 +1,87 @@ +--- +title : Modifiers +--- + +# Modifiers + +Modifiers can be used to limit the access of the class members scope. TypeScript has `public`, +`private` and `protected` modifier. + +### public +In TypeScript, you do not need to mark a member of a class `public`, each member is `public` by default. + +```typescript +class Tree { + public name: string; + public age: number; + public constructor(name:string, age:number){ + this.name = name; + this.age = number; + } + public detail(){ + console.log(`${this.name} is ${this.age} years old.`); + } +} + +``` + +### private +Sometimes you want to hide the member scope from outside classes. To do this, mark member of the class `private`. In TypeScript, `private` properties can't be accessed from outside the class scope. + +```typescript +class Tree { + private name: string; + private age: number; + constructor(name:string,age:number){ + this.name = name; + this.age = age; + } + } + + let tree = new Tree('Banyan', 102); + tree.name; // Error: 'name' is private; +``` + +### protected +The `protected` modifier acts like the `private` modifier with the exception that members declared `protected` can also be accessed within deriving classes. For example: + +```typescript +class Animal { + protected name:string; + protected constructor(name:string){ + this.name = name; + } +} + +class Cat extends Animal { + private color: string; + constructor(name:string,color:string){ + super(name); + this.color = color; + } + public getAnimalDetail(){ + return `Hello, my name is ${this.name} and my skin color is ${this.color}`; + } +} + +let lucy = new Cat("Lucy","White"); +let misty = new Animal("Misty"); // Error: The 'Animal' constructor is protected; +``` +### readonly +We can make members of the class read-only by using the `readonly` keyword. Read-only properties must be initialized at their declaration or in the constructor. + +```typescript +class SuperHero { + readonly name:string; + readonly author:string='Marvel'; + constructor(name:string){ + this.name = name; + } +} + +let hero = new SuperHero("Spider Man"); +hero.name = "Thor"; //Error: name is readonly; +``` + + +