남과 같이 해선 남 이상이 될 수 없다.

TypeScript

2021/06/22 TypeScript

맨동 2021. 6. 22. 13:08
728x90

readonly properties

readonly가 선언된 클래스 프로퍼티는 선언 시 또는 생성자 내부에서만 값을 할당할 수 있습니다.

그 외의 경우에는 값을 할당할 수 없고 오직 읽기만 가능한 상태가 됩니다.

 

//TS
class Person {
  public readonly name: string = 'Dongit';
  private readonly country: string = 'Korea';

  hello() {
    this.country = 'China'; // Cannot assign to 'country' because it is a constant or a read-only property.
  }
}
const p2 = new Person();
p2.name = "H.D" // Cannot assign to 'name' because it is a constant or a read-only property.

 

Class 안에서의 Index Signature

class Students {
  [index:string]: "male"|"female";

  mark:"male" = "male"; // 항상 mark는 male
}

const a = new Students();
a.mark="male";
a.jake="male";

const b= new Students();
b.anna="female";
b.park="male";

 

Singletons

Singleton 패턴은 Class로부터 단 하나의 오브젝트만 생성을 해서 사용하는 패턴

//TS
class ClassName {
  private static instance: ClassName | null = null;
  public static getInstance(): ClassName {
    // ClassName 으로부터 만든 object가 있으면 그걸 리턴
    // ClassName 으로부터 만든 object가 없으면 만든다.
    if (ClassName.instance === null) {
      ClassName.instance = new ClassName();
    }

    return ClassName.instance;
  }

  private constructor() { }
}

const a = ClassName.getInstance();
const b = ClassName.getInstance();

console.log(a === b);
//true

 

상속 (inheritance)

클래스의 상속은 extends 사용합니다.

Person을 상속받아서 KimPerson 을 만들고 name을 kim으로 강제로 적용시키는 코드입니다.

//TS
class Person {
  private hobbies: string[] = [];
  constructor(private readonly id: number, private name: string) { }

  show(this: Person) {
    console.log(`show ${this.id} , ${this.name}`)
  }

  addHobby(hobby: string) {
    this.hobbies.push(hobby);
  }
  showHobbies() {
    console.log(this.hobbies);
  }
}
class KimPerson extends Person {
  constructor(id: number) {
    super(id, "kim");
  }
}
const p = new KimPerson(5);
p.addHobby('game');
p.addHobby('running');

p.show(); //show 5 , kim
p.showHobbies(); // ["game","running"]

 

 

728x90

'TypeScript' 카테고리의 다른 글

[TypeScript] Property '...' does not exist on type 'DefaultRootState' - Redux type Error  (0) 2022.03.06
TypeScript - generic  (0) 2021.06.22
2021/06/21 TypeScript  (0) 2021.06.21
2021/06/19 TypeScript  (0) 2021.06.19
2021/06/17 TypeScript  (0) 2021.06.17