1. ts 可以使用访问控制符来保护对类、变量、方法和构造方法的访问
    2. ts 支持 3 种不同的访问权限
      1. **public**
        1. 公有
        2. 可以在任何地方被访问
        3. public 是默认值
      2. **protected**
        1. 受保护
        2. 可以被其自身以及其子类访问
      3. **private**
        1. 私有
        2. 只能被其定义所在的类访问
    1. class Encapsulate {
    2. str1: string = "hello"
    3. // public 是默认值,上述写法和下面这种写法等效
    4. // public str1: string = "hello"
    5. private str2: string = "world"
    6. }
    7. var obj = new Encapsulate()
    8. console.log(obj.str1) // 可访问
    9. console.log(obj.str2) // 编译错误, str2 是私有的
    10. // 报错:属性“str2”为私有属性,只能在类“Encapsulate”中访问。ts(2341)
    1. 类可以实现接口,使用关键字 implements
    1. // 定义一个接口
    2. interface IPerson {
    3. firstName: string;
    4. lastName: string;
    5. sayHello(): string;
    6. }
    7. // 创建一个类来实现这个接口
    8. class Person implements IPerson {
    9. firstName: string;
    10. lastName: string;
    11. constructor(firstName: string, lastName: string) {
    12. this.firstName = firstName;
    13. this.lastName = lastName;
    14. }
    15. // 实现接口中的方法
    16. sayHello(): string {
    17. return `Hello, my name is ${this.firstName} ${this.lastName}`;
    18. }
    19. }
    20. // 使用这个类
    21. const person = new Person("John", "Doe");
    22. console.log(person.sayHello());
    23. // Hello, my name is John Doe