타입스크립트에서 클래스를 사용할 때는 아래와 같이 타입을 지정해준다.
class Person {
name: string; // name 필드 값 미리 지정해줘야 constructor에서 선언 가능
// 리턴은 항상 오브젝트이기 때문에 리턴 타입은 굳이 명시 안해도 됨
constructor(name: string) {
this.name = name;
}
data = 0;
함수(x: string): void {
console.log(x);
}
}
let 사람1 = new Person("kim");
let 사람2 = new Person("park");
사람1.함수("hello");
class 클래스 {
// public 변수
public name;
age; // public은 명시하지 않아도 기본으로 설정돼있 음.
constructor(a) {
this.name = this.name;
}
// public 함수
public 함수() {
}
}
// 자식들은 public 변수 사용 가능
let 자식 = new 클래스("park");
자식.name = "hi";
class Person {
// 바로 name 변수에 할당
constructor(public name: string) {}
}
let 사람 = new Person("john");
console.log(사람.name); // 출력: john
private은 클래스 내에서만 사용이 가능하게 한다. 따라서 자식에서 수정이 불가능하다. 만약 클래스 외부에서 private 속성을 변경하려면 setter 함수를 만들어서 사용해야 한다.
class 클래스 {
// 클래스 내에서만 수정 가능
private name = "kim";
constructor() {
}
// 외부에서 private 속성 변경하려면 함수 만들어서 쓰기
이름변경함수(a: string) {
this.name = a;
}
}
protected는 속성을 extends된 클래스에서 사용 가능하게 한다.
class User {
protected x = 10;
}
class NewUser extends User {
doThis(){
console.log(this.x);
}
}
let x = new NewUser().doThis(); // 출력: 10
class 클래스 {
static x = 10;
}
let 자식 = new 클래스();
console.log(자식.x); // 에러: x가 존재하지 않음
console.log(클래스.x);
class 클래스 {
// static은 public, private와 같이 사용 가능
public static x = 10;
// static 변수는 this.변수로 사용하지 않고 클래스명.변수로 사용
y = 클래스.x + 10;
}
let 변수 = new 클래스();
console.log(변수); // 출력: 클래스 { y: 20 }
클래스.x = 30;
console.log(변수); // 출력: 클래스 { y: 20 }
let 변수2 = new 클래스();
console.log(변수2); // 출력: { y: 40 }
interface Square {
color: string;
width: number;
}
let 네모: Square = { color: "red", width: 100 };
위 예시의 인터페이스는 아래 type alias와 같은 기능을 한다.
type Square = { color: string; width: number };
interface Student {
name: String;
}
interface Teacher extends Student {
age: number;
}
let 학생: Student = { name: "kim" };
let 선생: Teacher = { name: "park", age: 20 };
// object 에 함수 저장할 수 있음
interface Operator {
plus: (a: number, b: number) => number;
minus: (a: number, b: number) => number;
}
let obj: Operator = {
plus(a, b) {
return a + b;
},
minus(a, b) {
return a - b;
},
};
type alias에서도 interface의 extends와 비슷한 기능이 있다. intersection type을 이용하는 것이다.
// intersection type 이용
type Animal = { name: string };
type Cat = { age: number } & Animal;
그러나, interface는 중복 선언 가능하지만, intersection은 불가능하다.
interface Student {
name: String;
}
interface Student { score: number };
위 코드에서 Student에 score 속성이 추가된다.
그리고 interface, type alias 둘 다 기존 속성 변경 불가능하다.
interface Student {
name: String;
}
interface Student { name: number }; // 에러
type Dog = { name: number } & Animal;
let 개: Dog = {name: 123} // 에러(never 타입)
보통 interface가 더 자주 사용된다.