클래스
동일한 모양의 객체를 더 쉽고 간결하게 만들어주는 "틀"의 역할.
필드, 생성자, 메서드 세 구간으로 나눌 수 있다.
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('working')
}
}
let employee = new Employee("사람1",20,"개발자");
- 클래스는 타입으로도 사용 가능
let employee: Employee = {
name:"이름",
age:20,
position:"개발자",
work(){ }
}
- 상속 가능 ( super의 등장 )
class MoreEm extends Employee {
officeNumber:number;
constructor(
name:string,
age:number,
position:string,
officeNumber:number
){
super(name,age,position); //최상단에 쓴다
this.officeNumber = officeNumber;
}
}
위에 만들어놨던 Employee 클래스를 상속받은 새로운 MoreEm 클래스를 만들었다.
super(원본 클래스의 프로퍼티들) 을 생성자함수 최상단에 꼭 넣어줘야한다.
- 접근제어자
public - 어디에서나 접근 가능 (굳이 쓰지 않아도 자동 설정됨)
private - 클래스 내부에서만 접근 가능
protected - 클래스 내부 & 파생 클래스에서 접근 가능
class Employee {
private name:string;
protected age:number;
public position:string;
constructor(name:string,age:number,position:string){
this.name=name;
this.age=age;
this.position=position;
}
work(){
console.log(`${this.name} 일함`) //name은 프라이빗이라서 class내부에서만 접근 가능
console.log(`${this.age}`)
}
}
class more extends Employee {
func(){
console.log(`${this.age}`) // age는 protected 라서 class내부와 파생class에서 접근 가능
}
}
const employee = new Employee("사람1",20,"developer")
employee.position = "디자이너" //position은 퍼블릭이라서 어디에서나 접근 가능
☘️코드를 조금 더 간단하게!
- 필드 생략 가능
class Employee {
constructor(public name:string, private age:number, protected position:string){}
work(){
console.log(`나이는 ${this.age} 입니다`) // private는 내부에서만 접근 가능
}
}
생성자함수 매개변수 넣는 곳에 접근제어자를 설정하면 자동으로 필드가 생성된다.
필드는 중복으로 설정할 수 없으므로 원래 필드가 있던 곳은 삭제 가능
그리고 생성자함수 내부의 this.필드 = 매개변수; 역시 자동으로 생성되기때문에 삭제 가능
- interface를 활용해 class 설계하기
interface Inter {
name:string;
movespeed:number;
move():void;
}
class Character implements Inter {
constructor (
public name:string,
public movespeed:number
) {}
move(){
console.log(`${this.name}의 속도는 ${this.movespeed}`)
}
}
interface를 사용해서 class에 사용될 필드와 메서드를 정의할 수 있다.
'개발 > typescript' 카테고리의 다른 글
타입스크립트 기초 문법 - 제네릭과 map,foreach 함수 (0) | 2024.01.03 |
---|---|
타입스크립트 기초 문법 - 제네릭 기초 (1) | 2024.01.02 |
타입스크립트 기초 문법 - 인터페이스 (1) | 2023.12.27 |
타입스크립트 기초 문법 - 함수 오버로딩, 사용자 정의 타입가드 (0) | 2023.12.27 |
타입스크립트 기초 문법 - 함수 타입과 호환성 (1) | 2023.12.27 |