Class Example1 - 클래스 만들기

2woongjae/ts-basic-class

class Person1 {
  name!: string;
  age!: number;
}

const person: Person1 = new Person1();
console.log(person); // Person1 {}
person.age = 35;
console.log(person.name); // undefined

* strictPropertyInitialization 의 중요성

--strictPropertyInitialization

Class Example2 - 클래스와 프로퍼티 (1)

2woongjae/ts-basic-class

class Person2 {
  name!: string;
  age!: number;

  constructor() {
    console.log(this.name === null); // false
    console.log(this.name === undefined); // true
  }
}

const person2: Person2 = new Person2();
person2.name = 'Mark';
person2.age = 36;
console.log(person2); // Person2 {name: 'Mark', age: 36}

Class Example3 - 클래스와 프로퍼티 (2)

2woongjae/ts-basic-class

class Person3 {
  name: string = 'Mark';
  age: number = 36;

  constructor() {
    console.log(this.name); // 'mark'
  }
}

const person3: Person3 = new Person3();
console.log(person3); // Person3 {name: 'Mark', age: 36}

Class Example4 - 클래스와 프로퍼티의 접근 제어자

2woongjae/ts-basic-class

class Person4 {
  public name!: string;
  private _age: number;

  constructor(age: number) {
    this._age = age;
  }
}

const person4: Person4 = new Person4(36);
person4.name = 'Mark';
// person._age (X)
console.log(person4); // Person {name: 'Mark', _age: 36}