타입스크립트의 클래스는 자바스크립트 클래스에 “타입정보”가 붙은 것이다. 실행시점에는 사실상 자바스크립트 클래스와 동일하게 동작한다.

클래스(Class)

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('일함')
  }
  work2(){
      console.log(`일함2${this.name}`)
  }
}
 const employee = {
    name: '희수',
    age: 27,
    position: 'developer',
    work(){
        console.log('작업중')
    }
}

속성 ‘’ 은 이니셜라이저가 없고 생성자에 할당되어 있지 않습니다.

타입스크립트에서는 클래스에 필드만 지정해놓으면 오류가난다. 어차피 undefind가 들어갈껀데 왜 만들었냐고 오류를 띄워주는 것

class Employee {
  // 필드
  name: string;
  age: number;
  position: string;
}

해결방법 1 선택적 프로퍼티로 만들기

class Employee {
  // 필드
  name?: string;
}

해결방법2 초기값 지정해주기

class Employee {
  // 필드
  name3:string = '';
}

해결방법 3 생성자 만들기

class Employee {
  // 필드
  name: string;
  age: number;
  position: string;
  
  // 생성자의 인수에도 타입을 지정해준다.
  constructor(name:string, age:number, position: string){
    this.name = name;
    this.age = age;
    this.position = position;
	}
}

클래스는 하나의 타입으로도 작용한다.

클래스는 자바스크립트 클래스로 취급되면서, 동시에 타입으로도 취급된다,

employeeB의 타입이 Employee로 추론되고있다.

const employeeB = new Employee('hihi',10,'개발자');
console.log(employeeB)

image.png

실제 타입으로도 지정가능하다 프로퍼티를 빠짐없이 사용해야하는것도 일반적인 타입과 동일하다.

const employeeC:Employee = {
    name:'안녕',
    age: 10,
    position: '안녕직업',
    work(){},
    work2(){}
}