본문 바로가기

Typescript/타입 기능

타입 Alias, Interface, Class

타입을 지정할 때 인라인으로 표기하는 방법외에도 Type, Interface, Class 을 이용하여 타입을 지정할 수 있다. 

이 방법을 사용하면 재사용성이 높아지게 된다.

 

Type Alias

type Info = {
  name: string,
  age: number
}
function printMe(param: Info){
	console.log(`${param.name} 의 나이는 ${param.age} 입니다.`)
}
printMe('개발자',32) // result => '개발자 나이는 32 입니다.'


/* 함수 자체의 타입도 정의 가능 */
type FunTest = (name:string) => string
function test(name: string, funParam: FunTest){
	console.log(funParam(name))
}
test('개발자') // result => '개발자'

 

Interface

인터페이스를 사용하면 이전 Type Alias 와 매우 비슷한지만 차이가 좀 있습니다. 

// 1. interface로 선언시 '=' 는 필요 하지 않다
interface Info {
  name: string,
  age: number
}



// 2. 처음 선언한 interface 에 추가적인 타입이 필요할 때 확장 가능하다.
interface Info {
  name: string,
  age: number
}
function funTest(param:Info){
  console.log(`${param.name},${param.age},${param.weight}`) 
}

funTest({name:'개발자',age:32, weight: 80}) // weight는 없으므로 컴파일시 에러 발생

interface Info {
  weight: number
}
funTest({name:'개발자',age:32, weight: 80}) // result => 개발자,32,80



// 3. extends를 사용하여 다른 인터페이스에 위임이 가능하다.
interface Info2 extends Info {
	height: string
}



// 4. class 에 implements 를 사용하여 위임 가능하다.
class Info3 implements Info {
  name: string,
  age: number,
  height: number // => Info에 선언 되어 있지 않아 error가 난다
}

 

인터페이스는 본인의 값 이외에 다른 필드나 메서드가 있음을 전제로 합니다. 그러나 타입 Alias는 객체의 타입 자체를 의미합니다. 

객체 그 자체가 아니라 클래스나 객체의 일부 속성, 함수를 포함하는 일부를 정의할 때는 인테페이스를 사용하는 것 이 적절합니다.

 

Class

Class TestClass {
  name: string;
  age: number;
  
  // 초깃값
  constructor(name: string = '', age: number = 0){
    this.name = name
    this.age = age
  }
  
  setName(name:string): void {
    this.name = name
  }
  
  setAge(age:number): void {
    this.age = age
  }
}

const myInfo = new testClass();
myInfo.setName('개발자')
console.log(`${name},${age}`)  // result => 개발자, 0


/* extends로 상속도 가능합니다. */
Class MyInfo extends TestClass {
  weight: number;
  
  constructor(name: string = '', age: number = 0, weight: number = 0){
    // 생성자 호출
    super(name,age)
    this.weight = weight
  }
  
  setWeight(weight: number):void {
    this.weight = weight
  }
}
const myInfo2 = new MyInfo()
myInfo2.setName('개발자')
myInfo.setWeight(80)
console.log(`${myInfo2.name},${myInfo2.weight},${myInfo2.age}`) // result => 개발자,80,0

 

Class 같은 경우 접근 수정자로 public, protected, private 를 제공합니다.

const myInfoDefault {
  public name: string;
  protected age : number;
  private weight: number;
}

const myInfoDefault = new MyInfoDefault()
myInfoDefault.name // OK
myInfoDefault.age // error, 컴파일 에러
myInfoDefault.weight //error, 컴파일 에러

// 상속 예시
class MyInfo extends myInfoDefault {
  contructor(){
    super()
    this.name // OK
    this.age // OK
    this.weight // error, 컴파일 에러
  }
}