반응형
SMALL
클래스(Class)
- object를 만드는 청사진, 설계도
- 클래스 이전에는 함수를 통해 객체를 만들었다.
- OOP(객체 지향 프로그래밍)을 위한 기본.
- TypeScript에서는 클래스도 타입의 하나이다.
class Human { //클래스의 이름은 대문자로 시작.
name;
constructor(name: string) {
this.name = name; //this는 생성된 객체 자신을 가리킴.
}
}
const h1 = new Human("Jack"): // 함수를 객체로 만들 때 처럼 new를 쓴다.
console.log(h1); // Human { name: "Jack"}
- class 키워드를 통해 생성 가능.
- 이름은 주로 대문자를 이용.
- new를 사용하여 object 생성.
- constructor를 이용하여 객체를 생성하면서 값을 전달 가능.
- es5의 경우 JS로 컴파일되면 function으로 변경됨.
constructor and initialize
class Human {
name: string = "Jack";
age: number; //Error
}
const h1 = new Human(): // h1의 타입은 Human.
console.log(h1);
age에 값을 할당해 주지 않으면 h1.age를 출력했을 때 undefined가 나온다.
age!: number; 를 하면 코드 실행 중에 값 할당이 이루어진다는 것을 의미하므로 에러가 뜨지 않는다.
class Human {
name: string = "Jack";
age: number;
constructor(age: number) {
this.age = age;
}
}
const h1 = new Human(20):
console.log(h1);
console.log(h1.age);
- 생성자 앞에는 async를 붙일 수 없다.
- 생성자 함수가 없으면 디폴트 생성자라 불린다.
- strict모드에서는 선언하는 곳 이나 생성자에서 값을 할당해야 한다.
- 그렇지 않는 경우! 를 붙인다.
- 프로퍼티가 정의되어 있지만, 값을 대입하지 않으면 undefined이다.
접근 제어자 (Access Modifiers)
class Human {
public name: string = "Jack";
private _age: number;
constructor(age?: number) {
if (age === undefined) {
this.age = 0;
} else {
this.age = age;
}
}
public async init() {}
}
const h1 = new Human(20):
console.log(h1);
console.log(h1.age); // 사용 불가!
- public, private, protected
- 기본으로 public 이다.
- 생성자, 프로퍼티, 메서드 모두 설정이 가능하다.
- private로 설정하면 외부에서 접근할 수 없다.
- JS에서는 private를 지원하지 않아 이름 앞에 _를 붙여서 표현했다.
Getters & Setters
class Human {
public constructor(private _name: string, private age: number) {}
get name() {
return this._name;
}
set name(n: string) {
this._name = n;
}
}
const h1 = new Human("Jack", 30):
console.log(h1.name); //getter
h1.name = "Mike"; //setter
readonly property
class Human {
public readonly name: string = "James"; // 클래스 밖에서 변수 값 변경 불가.
private readonly gender: string;
public constructor(private _name: string, private age: number) {
this.gender = "M";
}
func1() {
this.gender = "W"; // Error
}
}
const h1 = new Human("Jack", 30):
console.log(h1.name);
h1.name = "Mike"; // Error
readonly가 붙으면 초기화가 되는 영역에서만 값 설정이 가능하다.
프로퍼티를 초기값으로 정하고 수정하고 싶지 않을 때 사용한다.
상속(Inheritance)
클래스가 다른 클래스를 가져다가 자신의 기능을 추가하여 사용하는 것.
class Parent {
constructor(protected _name: string, private _age: number) {} //상속관계만 접근 가능.
public print(): void {
console.log(`${this._name}, ${this._age}.`);
}
}
class Child extends Parent {
public country = "korea";
constructor(age: number) {
super('Anna', age); // 부모의 생성자 호출.
// 자식 생성자에서는 super를 먼저 해 주어야 함.
}
}
const c = new Child(1);
c.print(); // Anna, 1
반응형
'프론트개발 > TypeScript' 카테고리의 다른 글
[TypeScript] 인터페이스(Interface) (0) | 2022.07.19 |
---|---|
[TypeScript] 타입 호환성과 별칭 (0) | 2022.07.18 |
[TypeScript] 타입 시스템 (0) | 2022.07.18 |
[TypeScript] 타입 스크립트의 타입(2) (0) | 2022.07.16 |
[TypeScript] 타입 스크립트의 타입(1) (0) | 2022.07.16 |
댓글