TypeScript

코드생성과 타입은 관계가 없음

milliwonkim 2022. 6. 19. 00:35
반응형
SMALL

타입스크립트 컴파일러 역할

  • 최신 타입스크립트/자바스크립트를 브라우저에서 동작할 수 있도록 ⇒ 구버전의 자바스크립트로 트랜스파일
    • 트랜스파일 = translate + compile
      • 여전히 컴파일되야하는 코드이기 때문에 컴파일과 분리되어 용어가 설명됨
  • 코드 타입 오류 체크

⇒ 서로 완벽히 독립적

  • 타입스크립트가 자바스크립트로 변환될 때 코드 타입에는 영향을 주지 않음
  • 자바스크립트 실행시점에도 타입은 영향을 미치지 않음

 

런타임에는 타입체크가 불가능

instanceof 체크는 런타임에 일어나지만, Rectangle은 타입이라서 런타임에는 아무런 영향이 없음. 따라서 해당 오류가 발생

// 'Rectangle' only refers to a type, but is being used as a value here.(2693)
interface Square {
    width: number;
}

interface Rectangle extends Square {
    height: number;
}

type Shape = Square | Rectangle;

function calculateArea(shape: Shape) {
    if(shape instanceof Rectangle) {
        return shape.width * shape.height;
    }

    return shape.width * shape.width;
}

자바스크립트로 컴파일 과정 시, 모든 타입스크립트 구문은 사라짐

shape의 타입을 명시적으로 하고 싶다면 다음의 방법들이 있음

  • 타입정보를 명시적으로 적는 태그 기법
  • 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') { return shape.width * shape.height; } return shape.width * shape.width; }
  • 타입을 클래스로 만들기
    class Square {
        constructor(public width: number) {}
    }
    
    class Rectangle extends Square {
        constructor(public width: number, public height: number) {
            super(width)
        }
    }
    
    // 여기에서는 Rectangle이 타입으로 참조됨
    type Shape = Square | Rectangle; 
    
    function calculateArea(shape: Shape) {
    // 여기서는 Rectangle이 값으로 참조됨
        if(shape instanceof Rectangle) {
            shape; // 타입이 Rectangle
            return shape.width * shape.height;
        } else {
            shape; // 타입이 Square
            return shape.width * shape.width;
        }
    }
    
  • 타입(런타임 접근 불가)과 값(런타임 접근 가능)을 둘다 사용할 수 있습니다.

 

타입으로는 함수를 오버로드할 수 없음

// Duplicate function implementation.(2393)
function add(a: number, b: number): number {
    return a + b
}

// Duplicate function implementation.(2393)
function add(a: string, b: string): string {
    return a + b
}

 

 

타입스크립트 타입은 런타임 성능에 영향을 주지 않음

  • 타입, 타입 연산자는 자바스크립트 변환 시점에 제거돼서, 런타임에는 아무런 영햐을 주지 않음

 

타입오류 코드도 컴파일 가능

 

any 타입 지양

반응형
LIST