string, number 등)?로 지정super()는 생성자의 첫 줄에서 호출해야 함타입스크립트에서는 클래스의 필드를 선언할 때 타입 주석을 함께 명시해야 한다.
그렇지 않으면 암시적으로 any 타입으로 추론되며, strict 모드에서는 오류가 발생한다.
또한 생성자에서 초기화하지 않을 경우, 필드 선언 시 초기값을 명시해야 한다.
class Employee {
// 필드
name: string = "";
age: number = 0;
position: string = "";
// 메서드
work() {
console.log("일함");
}
}
생성자에서 필드의 값을 초기화하면, 필드 선언 시 초기값은 생략 가능하다.
class Employee {
name: string;
age: number;
position: string;
constructor(name: string, age: number, position: string) {
this.name = name;
this.age = age;
this.position = position;
}
work() {
console.log("일함");
}
}
특정 프로퍼티를 선택적으로 만들고 싶다면 ?를 붙이면 된다.
class Employee {
name: string;
age: number;
position?: string;
constructor(name: string, age: number, position?: string) {
this.name = name;
this.age = age;
this.position = position;
}
work() {
console.log("일함");
}
}
클래스는 타입으로도 사용할 수 있다.
즉, 해당 클래스가 생성하는 객체의 모양(프로퍼티/메서드)을 타입으로 사용 가능하다.
class Employee {
name: string;
age: number;
position: string;
constructor(name: string, age: number, position: string) {
this.name = name;
this.age = age;
this.position = position;
}
work() {
console.log("일함");
}
}
const employeeC: Employee = {
name: "",
age: 0,
position: "",
work() {},
};
employeeC는 Employee 클래스를 타입으로 지정했기 때문에,
동일한 구조의 객체로 취급된다.
타입스크립트에서도 클래스의 상속(extends) 을 사용할 수 있다.
하위 클래스에서 생성자를 선언하면 반드시 super()를 호출해야 하며,
이 호출은 생성자의 최상단에서 실행되어야 한다.
class ExecutiveOfficer extends Employee {
officeNumber: number;
constructor(
name: string,
age: number,
position: string,
officeNumber: number
) {
super(name, age, position); // 반드시 최상단에서 호출
this.officeNumber = officeNumber;
}
}