TypeScript Crash Course: Property Access Modifiers

There is no other great moment to head into the world of TypeScript instead of right now. Angular is in TypeScript, React is in TypeScript, and even Vue3 is in TypeScript. That means its a skill we must equip with rather than wait and see.

This is the first post of my own TypeScript crash course, chances that its your jam, stay tune;)

public, private, protected and readonly access modifier

Define properties through constructor parameters

Its way too boring to put values into the properties when construct an instance like below

代码语言:javascript
AI代码解释
复制
class User { private readonly idCard: string protected name: string age: number constructor(idCard: string, name: string, age: number) { this.idCard = idCard this.name = name this.age = age } }

Fortunately, TypeScript has done that for us. When we specify public, private or other access modifiers on the constructor parameters, a corresponding property is created on the class and filled with the value of the parameter. So we could make the previous one much damn shorter like this.

代码语言:javascript
AI代码解释
复制
class User { constructor(private readonly idCard: string, protected name: string, public age: number) {} }

Pretty cool yet;)

上一篇 Another Intro for Cookies
下一篇 Yet Another Intro for Symbol