Class의 타입지정

김범주·2022년 7월 13일
0

typescript

목록 보기
7/23
post-thumbnail
class Person {
  name;
  age;
  constructor (){
    this.name = 'kim';
    this.age = 20;
  }
}

타입스크립트의 클래스 타입지정은 자바스크립트와 형태가 비슷하지만 this.속성을 정할 때 필드 값으로 그 속성이 미리 정의되어있어야 사용가능함

class Person {
  name;
  age;
  constructor ( a :string ){
    this.name = a;
    this.age = 20;
  }
}

이런 식으로 함수처럼 파라미터에 타입지정도 가능

활용예시

class Car {
  model :string;
  price :number;
  constructor(a :string, b :number){
    this.model = a;
    this.price = b;
  }

  tax() :number{
    return this.price * 0.1
  }
}


let car1 = new Car('소나타', 3000)
console.log(car1) //콘솔창 출력결과는 { model : '소나타', price : 3000 }
console.log(car1.tax()) //콘솔창 출력결과는 300
profile
개발꿈나무

0개의 댓글