반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

ts와 타입의 관계 이해 본문

TS/이펙티브 타입스크립트

ts와 타입의 관계 이해

5_hyun 2023. 1. 4. 00:23

TS 컴파일러

-TS 컴파일러의 역할

1. 최신 js/ts가 동작하게끔 구버전 js로 트랜스파일(translate+compile)한다.

2. 코드의 타입 오류를 체크해준다.

 

위 역할 두 가지는 독립적이다.

즉, ts가 js로 변환될 때 코드에 있는 타입에는 영향을 주지 않는다. 그리고 변환된 js 실행에서도 타입은 영향을 끼치지 않는다.

타입 오류가 있는 코드

let x = "abcd";
x = 1234;

컴파일과 타입 체크가 독립적이라서, 위 코드처럼 타임 오류가 있어도 컴파일이 가능하다. 

코드에 오류가 있더라도 컴파일된 결과가 나오는 것이 도움이 된다. 웹을 만들 때, 오류가 해결되지 않아도 다른 부분을 테스트할 수 있다.

런타임과 타입 체크

ts에서 js로 컴파일되는 과정에서 interface, type, type 구문들은 제거가 된다. 그렇기에 타입을 명확하게 하려면 런타임에 타입 정보를 유지할 수 있어야 한다.

속성이 존재하는지 체크

-ts 파일

interface Square {
  width: number
}
interface Rectangle extends Square {
  height: number
}
type Shape = Square | Rectangle

function calculateArea(shape: Shape) {
  if ('height' in shape) {
    shape
    return shape.width * shape.height
  } else {
    shape 
    return shape.width * shape.width
  }
}

위 코드처럼 height 속성이 존재하는지 체크해보면 shape 타입을 명확히 할 수 있다.

 

-js로 변환된 파일

function calculateArea(shape) {
    if ('height' in shape) {
        shape; // Type is Rectangle
        return shape.width * shape.height;
    }
    else {
        shape; // Type is Square
        return shape.width * shape.width;
    }
}

이 코드는 "tsc 파일명" 해서 js로 변환해 본 것이다. "height"가 영향을 끼치고 있는 것을 볼 수 있다.

태그 기법

-ts 파일

interface Square {
  kind: 'square'
  width: number
}
interface Rectangle {
  kind: 'rectangle'
  height: number
  width: number
}
type Shape = Square | Rectangle

function calculateArea(shape: Shape) {
  if (shape.kind === 'rectangle') {
    shape // Type is Rectangle
    return shape.width * shape.height
  } else {
    shape // Type is Square
    return shape.width * shape.width
  }
}

Shape 타입은 "tagged union"의 예시이다. 이렇게 코드를 작성하면 타입 정보를 쉽게 유지할 수 있어서 자주 사용된다.

 

-js로 변환된 파일

function calculateArea(shape) {
    if (shape.kind === 'rectangle') {
        shape; // Type is Rectangle
        return shape.width * shape.height;
    }
    else {
        shape; // Type is Square
        return shape.width * shape.width;
    }
}

클래스 사용 기법

class Square {
  constructor(public width: number) {}
}
class Rectangle extends Square {
  constructor(public width: number, public height: number) {
    super(width)
  }
}
type Shape = Square | Rectangle

function calculateArea(shape: Shape) {
  if (shape instanceof Rectangle) {
    shape // Type is Rectangle
    return shape.width * shape.height
  } else {
    shape // Type is Square
    return shape.width * shape.width // OK
  }
}

class를 사용하면 타입과 값을 모두 사용할 수 있어서 오류가 없다. shape instanceof Rectangle에서는 값으로 참조된다.

TS 타입과 함수 오버로드

TS 타입으로는 함수 오버로드를 할 수 없다. 왜냐하면 TS에서는 타입과 런타임의 동작이 무관하기 때문이다.

TS 타입과 런타임 성능

TS 타입은 런타임 성능에 영향을 주지 않는다. 왜냐하면 JS로 변환할 때, 타입과 타입 연산자는 제거되기 때문이다.

728x90
반응형

'TS > 이펙티브 타입스크립트' 카테고리의 다른 글

타입 선언문과 단언문  (0) 2023.02.10
타입과 값 구분하기  (0) 2023.02.10
TS의 타입  (0) 2023.01.21
구조적 타이핑  (0) 2023.01.17
TS와 JS, TS 설정  (0) 2023.01.02
Comments