타입스크립트 4.3 버전에서는 어떤 점들이 변경되었을까?

dante Yoon·2021년 5월 27일
post-thumbnail

#typescript

#4.3

어제 타입스크립트 4.3 업데이트가 npm에 올라왔고 레딧을 통해 소개되었습니다.

https://devblogs.microsoft.com/typescript/announcing-typescript-4-3-rc/#separate-write-types

Today we’re excited to announce our Release Candidate (RC) of TypeScript 4.3! Between now and the stable release of TypeScript 4.3, we expect no further changes apart from critical bug fixes. To get started using the RC, you can get it through NuGet,

devblogs.microsoft.com

위의 마소 블로그를 읽고 개인적으로 주요 변경점이라 생각되는 점을 정리해보았습니다.

클래스 오버라이드 시 override 키워드를 명시적으로 적어주게 됨

class SuperClass {
  //copy(){
  //}
  
  //paste(){
  //}

  copyAndPaste(){
  }  
}

class SubClass extends SuperClass {
  copy() {
  }

  paste() {
  } 
}

상속 관계에서 자식 클래스는 부모 클래스의 메소드를 오버라이드 할 수 있습니다.

만약 부모클래스에서 코드리팩토링을 통해 자식클래스에서 오버라이드하고 있는 메소드를 없애거나 변경하게 된다면

자식클래스를 사용하는 입장에서는 기존에 어떤 메소드들이 오버라이드 되고 있으며 어떠한 부분을 같이 수정해야 하는지 파악하기 어렵다는 문제가 발생합니다.

class SomeComponent {
    setVisible(value: boolean) {
        // ...
    }
}
class SpecializedComponent extends SomeComponent {
    override show() {
//  ~~~~~~~~
// Error! This method can't be marked with 'override' because it's not declared in 'SomeComponent'.
        // ...
    }

    // ...
}

따라서 위와 같이 override 키워드를 명시적으로 적어주게 되면 리팩토링을 통한 오류를 줄일 수 있습니다.

만약 유저가 override 키워드를 생략한다면 위와 같은 새로운 피처의 도움을 받을 수 없게 될텐데요,

--noImplicitOverride 플래그를 통해 override 키워드를 필수 적용하게 시킬 수 있습니다.

template-string-type-improvements

한가지 또 눈에 띄는 점은 template-string-type-improvements 입니다.

https://devblogs.microsoft.com/typescript/announcing-typescript-4-3-rc/#template-string-type-improvements

타입 스크립트에서는 일반 스트링도 하나의 타입으로 선언하여 type alias를 통해 여러 스트링의 묶음을 하나의 타입으로 지정할 수 있습니다.

type cardType = "samsung" | "hana" | "student"

문제는 나중에 카드 타입이 추가되거나 타입의 종류가 세분화된다면 추가적으로 cardType에 하드코딩으로 일일히 스트링을 입력해주어야 한다는 점입니다.

type Promotion = "premium" | "standard";
type Color = "blue" | "yellow";

type CardType = `${Promotion | Color} card`;
// same as
//   type CardType = "premium card" | "standard card
//                  | "blue card" | "yellow card";

하지만 위의 예제코드처럼 CardType에서 사용할 세분화된 타입들을 미리 지정해둔다면 CardType의 조합은 조금 더 다채롭고 편하게 만들어질 수 있습니다.

Always -Truthy Promise check

Promise를 리턴하는 함수는 리턴 값의 타입이 nullish 하지 않기 때문에 조건문에 반환값을 조건으로 넣어줄 경우 항상 truthy 한 로직으로 판단이 됩니다. 따라서 반환값 그 자체만으로는 무의미한 조건식이 되는데 이 부분에 대해 타입스크립트에서 경고문을 띄워주지 않았습니다.

4.3 버전 부터 Promise를 단일 조건으로 조건문 안에 넣을 경우 await 을 빼먹지는 않았는지 경고가 나오게 됩니다.

https://github.com/microsoft/TypeScript/pull/39175

async function foo(): Promise<boolean> {
    return false;
}

async function bar(): Promise<string> {
    if (foo()) {
    //  ~~~~~
    // Error!
    // This condition will always return true since
    // this 'Promise<boolean>' appears to always be defined.
    // Did you forget to use 'await'?
        return "true";
    }
    return "false";
}

Static Index Signature

4.3 버전 이전의 타입 스크립트에서 클래스의 인덱스 시그니처는 오직 클래스 내부 인스턴스에만 적용이 되고 static 인스턴스에는 적용이 되지 않았습니다.

interface SomethingInterface {
  [key: string] : number; 
}

// Class 'Something' incorrectly implements interface 'SomethingInterface'.
// Index signature is missing in type 'Something'.ts(2420)
class Something implements SomethingInterface {
  static staticKey: string = "something";
}

4.3 버전부터는 static 인스턴스를 대상으로 인덱스 시그니처 타입을 정의할 수 있습니다.

class Foo {
    static hello = "hello";
    static world = 1234;

    static [propName: string]: string | number | undefined;
}

Import Statement Completions

es6 문법을 이용해 모듈을 임포트 할 때는 import somethinf from "file" 과 같은 문법을 사용하게 됩니다.

import { func } from "./module.js";

문제는 가져오려는 모듈의 위치를 임포트 구문 전체를 적지 않는 한 IDE에서 알지 못해 키워드 자동생성의 이점을 전혀 사용하지 못한다는 점입니다.

임포트 구문을 파이썬처럼 사용할 수 있게 되었습니다!

from "./module.js" import { func };
profile
성장을 향한 작은 몸부림의 흔적들

0개의 댓글