首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >TypeScript Crash Course: Property Access Modifiers

TypeScript Crash Course: Property Access Modifiers

作者头像
^_^肥仔John
发布2021-12-01 10:23:14
2490
发布2021-12-01 10:23:14
举报

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 it's a skill we must equip with rather than wait and see.

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

public, private, protected and readonly access modifier

Define properties through constructor parameters

It's way too boring to put values into the properties when construct an instance like below

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.

class User {
    constructor(private readonly idCard: string, protected name: string, public age: number) {}
}

Pretty cool yet;)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-11-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • public, private, protected and readonly access modifier
  • Define properties through constructor parameters
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档