기록하는 타입스크립트 - Class

FeelingXD·2022년 11월 17일
0
post-thumbnail

Class

자바스크립트 ES6부터 class 문법이추가되었습니다. 자바스크립트에서 생성자로 인해 생긴 프로퍼티 또한 인식하였으나 타입스크립트에서 내부에서 사용하는 프로퍼티또안 선언한뒤 사용해야합니다.

class Person{ // in javascript ! 
  constructor(name){
    this.name =name //생성자로 값 초기화 와 동시에 선언
  }
}

타입스크립트에서..

class Person{// in typescript
	name:string // 프로퍼티 사용전 선언
  constructor(name:string){
	this.name=name  //생성자로 값 초기화
	}
} 

접근제어자

public ,protected, private

typescript의 경우, 접근 제한자를 생략한 클래스 프로퍼티와 메소드는 암묵적으로 public이 선언된다. 따라서 public으로 지정하고자 하는 멤버 변수와 메소드는 접근 제한자를 생략한다.

접근 제한자를 선언한 프로퍼티와 메소드에 대한 접근 가능성은 아래와 같다.

접근가능publicprotectprivate
클래스 내부✔️✔️✔️
자식 클래스✔️✔️
클래스 인스턴스✔️

접근제한자를 사용한 생성자 피라미터는 암묵적으로 초기화가 같이 시행된다.

class Person{
	constructor(public name: name,protect age:number, private hobby:string){
    		this.name =name
      		this.age=age
      		this.hobby=hobby
    }
}

위와같이 따로 프로퍼티를 선언해주지않더라도 접근제어자가 사용된경우 타입스크립트에서 암묵적으로 선언&초기화가 진행된다.

readonly

Typescript는 readonly 키워드를 사용할 수 있다. readonly이 선언된 프로퍼티는 선언, 생성자 내부에서만 값을 변경할수있으며 그외에는 오직 읽기만가능하다.

class Person{
  private readonly name
	constructor(name:string){
    	this.name = name
    }
}

static ?

static 은 클래스의 인스턴스 없이 호출이 가능하며 클래스가 인스턴스화되면 호출할 수 없다. 정적 메서드는 종종 어플리케이션의 유틸리티 함수를 만드는데 사용된다.

	class Circle{
        static pi:number =3.14
        constructor(public radius:number){}
      
      area(){
      	return this.radius**2*Circle.pi
      }
    }

	

abstract 추상클래스

abstract 추론타입 또한 타입스크립트에서 사용할수있다.
아래의 코드는 Person 을 추상클래스로 만들었으며 American 이라는 구체 클래스의 토대가 되었다. 추상클래스는 추후 상속받는 구체클래스 공통적인 동작들을 정의하기위해 사용되는 기술이다.

추상클래스는 다음과 같은 특징이 있다.

  • 추상 클래스의 객체 인스턴스를 생성할 수 없습니다.
  • 추상 함수는 추상 클래스에서 정의합니다.
  • 추상 함수의 구현은 구체 클래스에서 구현합니다.
abstract class Person{
	name:string
    constructor(name:string)
    {
        this.name=name
    }
  	sayhello(country:string){
    	console.log(`hi myname is ${this.name}` + country)
    }
}

class American extends Person{
    constructor(name:string){
        super(name)
    }
    
    sayHello(){
        return `hi myname is ${this.name} imma American`
    }
}

class Korean extends Person{
    constructor(name:string){
        super(name)
    }
    sayHello(){
        return `hi myname is ${this.name} imma Korean`
    }

}
const jack = new American(`jack`)
jack.sayhello() // -> "hi myname is jack imma American" 
const jimin = new Korean(`jimin`)
jimin.sayHello() // -> "hi myname is jimin imma Korean"
profile
tistory로 이사갑니다. :) https://feelingxd.tistory.com/

0개의 댓글