ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 타입스크립트 5.0 베타 요약
    Study/개발 2023. 2. 6. 02:00

    Announcing TypeScript 5.0 Beta

     

    Announcing TypeScript 5.0 Beta

    Today we’re excited to announce our beta release of TypeScript 5.0! This release brings many new features, while aiming to make TypeScript, smaller, simpler, and faster. We’ve implemented the new decorators standard, functionality to better support ESM

    devblogs.microsoft.com

    참고 내용 - 마이크로소프트 타입스크립트 블로그. 위 글에 각 내용들이 상세하게 정리되어 있으니 상세설명은 글을 읽어 보는 것을 추천.

     

     

    데코레이터

    --experimentalDecorator를 추가해서 사용해야했던 데코레이터가 이번 버전에서 정식 기능으로 추가된다.

    ex)

    class Person {
        name: string;
        constructor(name: string) {
            this.name = name;
        }
    
        @loggedMethod
        greet() {
            console.log(`Hello, my name is ${this.name}.`);
        }
    }

     

    const 타입 패러미터

    as const 를 통해서 변경 불가한 타입으로 추론할 수 있었다.

    이번 버전에서 추가된 const 키워드는 타입 패러미터 선언에서 위와 유사한 행동을 할 수 있다.

    ex)

    type HasNames = { readonly names: string[] };
    function getNamesExactly<T extends HasNames>(arg: T): T["names"] {
        return arg.names;
    }
    
    // Inferred type: string[]
    const names = getNamesExactly({ names: ["Alice", "Bob", "Eve"]});

    readonly ["Alice", "Bob", "Eve"] 으로 추론되길 원하지만 string[]으로 추론된다.

    새로 추가된 const 키워드를 사용하면 아래와 같이 쓸 수 있다.

    function getNamesExactly<const T extends HasNames>(arg: T): T["names"] {
    //                       ^^^^^
        return arg.names;
    }
    
    // Inferred type: readonly ["Alice", "Bob", "Eve"]
    // Note: Didn't need to write 'as const' here
    const names = getNamesExactly({ names: ["Alice", "Bob", "Eve"] });

    주의 - 함수 호출 밖에서 선언된 객체에 대해서는 기존과 같이 동작한다.

    declare function fnGood<const T extends readonly string[]>(args: T): void;
    const arr = ["a", "b" ,"c"];
    
    // 'T' is still 'string[]'-- the 'const' modifier has no effect here
    fnGood(arr);

    extends multiple config file 지원

    {
        "compilerOptions": {
            "extends": ["a", "b", "c"]
        }
    }

    중복되는 설정값의 경우 뒤에 오는 설정의 값을 따르게 된다.

     

     

    모든 enum은 union enum이다.

    타입스크립트에서 enum을 취급하는 방식에는 두 가지가 있다.

    • Numeric 방식 (초기 방식) - 계산된 값을 가질 수 있음.
    • Literal (union) 방식 (TS 2버전부터 도입된 방식) - 리터럴값만 가질 수 있음

    두 방식을 합쳐서 이제는 모든 enum이 union 방식의 enum 으로 동작한다.

    ex)

    enum E {
        A = 10 * 10,  // Numeric literal enum member
        B = "foo",    // String literal enum member
        C = bar(42)   // Opaque computed enum member
    }

    E 타입선언의 경우, 타입 E.A, E.B, E.C를 각각 선언하고, EE.A | E.B | E.C와 같이 union으로 정의한다.

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

    --moduleResolution bundler

    {
        "compilerOptions": {
            "target": "esnext",
            "moduleResolution": "bundler"
        }
    }

    모던 번들러에서 모듈을 resolution하는 방식과 잘 호환될 수 있도록 hybrid lookup strategy를 사용하는 새로운 모듈 resolution 방식이다.

     

     

    Resolution Customization Flags

    위의 bundler 모드 처럼 자바스크립트 개발도구들은 hybrid resolution rule을 사용하기도 한다. 각 툴마다 지원이 조금씩 다를 수 있기 때문에 관련 설정 옵션들을 제공한다.

    • allowImportingTsExtensions
    • resolvePackageJsonExports
    • resolvePackageJsonImports
    • allowArbitraryExtensions

     

    --verbatimModuleSyntax

    Module elision 동작을 더 명확하고 간단하게 사용할 수 있도록 해주는 옵션.

    cf) Module elision: 타입스크립트가 모듈을 가져올 때, 타입만을 가져오는 경우, 변환된 JS에서는 그 import를 제거한다.

    // Erased away entirely.
    import type { A } from "a";
    
    // Rewritten to 'import { b } from "bcd";'
    import { b, type c, type d } from "bcd";
    
    // Rewritten to 'import {} from "xyz";'
    import { type xyz } from "xyz";

     

     

    export type * 지원

    ex)

    // models/vehicles.ts
    export class Spaceship {
      // ...
    }
    
    // models/index.ts
    export type * as vehicles from "./spaceship";
    
    // main.ts
    import { vehicles } from "./models";
    
    function takeASpaceship(s: vehicles.Spaceship) {
      //  ok - `vehicles` only used in a type position
    }
    
    function makeASpaceship() {
      return new vehicles.Spaceship();
      //         ^^^^^^^^
      // 'vehicles' cannot be used as a value because it was exported using 'export type'.
      // 타입만 내보냈기 때문에 값은 사용 불가능
    }

     

     

    JSDoc @satisfies 지원

    TypeScript 4.9에서 추가된 오퍼레이터인 satisfies를 JSDoc에서도 사용할 수 있게 되었다.

    ex)

    // @ts-check
    
    /**
     * @typedef CompilerOptions
     * @prop {boolean} [strict]
     * @prop {string} [outDir]
     * @prop {string | string[]} [extends]
     */
    
    /**
     * @satisfies {CompilerOptions}
     */
    let myCompilerOptions = {
        strict: true,
        outDir: "../lib",
        extends: [
            "@tsconfig/strictest/tsconfig.json",
            "../../../tsconfig.base.json"
        ],
    };
    
    // extends가 string[]으로 맞게 추론됨
    let inheritedConfigs = myCompilerOptions.extends.map(resolveConfig);
    // 인라인 형태 예시
    
    let myCompilerOptions = /** @satisfies {CompilerOptions} */ ({
        strict: true,
        outDir: "../lib",
        extends: [
            "@tsconfig/strictest/tsconfig.json",
            "../../../tsconfig.base.json"
        ],
    });

     

     

    JSDoc @overload 지원

    함수의 오버로드를 JSDoc형태로도 사용할 수 있게 되었다.

    // @ts-check
    
    /**
     * @overload
     * @param {string} value
     * @return {void}
     */
    
    /**
     * @overload
     * @param {number} value
     * @param {number} [maximumFractionDigits]
     * @return {void}
     */
    
    /**
     * @param {string | number} value
     * @param {number} [maximumFractionDigits]
     */
    function printValue(value, maximumFractionDigits) {
        if (typeof value === "number") {
            const formatter = Intl.NumberFormat("en-US", {
                maximumFractionDigits,
            });
            value = formatter.format(value);
        }
    
        console.log(value);
    }

     

     

    --build Flag 추가

    emit과 관련된 플래그들이 추가되었다.

    • -declaration
    • -emitDeclarationOnly
    • -declarationMap
    • -soureMap
    • -inlineSourceMap
    tsc --build -p ./my-project-dir --declaration

    switch/ case 자동완성

    타입스크립트가 switch 문에서 체크하는 값이 literal인 경우, uncovered 케이스의 자동완성을 제공한다.

    원본 블로그의 이미지

     

     

    성능, 메모리, 패키지 사이즈 최적화

    • TS 인스톨의 속도 향상
    • 패키지 빌드 속도 향상

    그 외, 새로운 deprecations, breaking changes 등도 적혀있다.

    728x90
Designed by Tistory.