BlogApplicationsGuestbook

Github | X (Twitter)

Copyright © 2024 OPNay - All Reserved | Privacy Policy

TypeScript 5.2 업데이트

2023.08.28 04:05

x

지난 8월 24일 TypeScript 5.2가 출시했습니다. 주요 변경사항은 using 키워드 지원, 데코레이터에 메타데이터 추가, 배열 복사 메서드 추가 등이 있습니다.

using 키워드 추가

지난 게시글에서 소개한 자원 관리를 위한 키워드 using 이 추가되었습니다. let, const 대신 사용하는 변수 선언 키워드로, Symbol.dispose, Symbol.asyncDispose 로 된 속성 값이 있는 객체를 대상으로 사용할 수 있습니다.

{ using resource = getResource(); using reader = resource.getReader(); const { value, done } = reader.read(); } // 블록을 벗어날 때 'reader' => 'resource' 순으로 자원 해제
typescript

tc39에 제안된 내용이며, 다음 ECMAScript에서 볼 수도 있는 Stage 3 후보 상태입니다. 물론 후보 상태이므로, tsconfig.json 에서 compilerOptions.lib 배열에 esnext 혹은 esnext.disposable 을 추가해야지만 사용가능합니다.

 

데코레이터에 메타데이터 추가

지난 5.0에서 tc39 제안 내용에 맞춰 데코레이터가 새롭게 만들어 졌습니다. 이에 대한 후속 제안으로 메타데이터가 추가되었습니다.

데코레이터의 두번째 파라미터인 context 에서 metadata 라는 빈 객체가 할당되어 있으며, 이는 자유롭게 속성에 할당이 가능하고, 외부에서의 접근은 Symbol.metadata 를 통해 하실 수 있습니다.

interface Context { name: string; metadata: Record; } function setMetadata(_target: any, context: Context) { context.metadata[context.name] = true; } class SomeClass { @setMetadata foo = 123; @setMetadata accessor bar = "hello!"; @setMetadata baz() { } } const ourMetadata = SomeClass[Symbol.metadata]; console.log(JSON.stringify(ourMetadata)); // { "bar": true, "baz": true, "foo": true }
typescript

데코레이터 메타데이터 예제

익명, 이름을 가진 튜플 혼합 지원

기존 타입스크립트에는 튜플 요소에 이름을 지을 수 있었습니다. 하지만, “무조건” 모든 요소에 이름을 지어야지만 사용이 가능했습니다. 이번 5.2에서는 이러한 제한이 해제됩니다.

// before 5.2, ✅ Possible type Pair = [first: string, second: number]; // before 5.2, ❌ has an error type Pair = [first: string, number]; type Args = [first: string, ...string[]]; // after 5.2, ✅ Possible type Pair = [first: string, number]; type Args = [first: string, ...string[]];
typescript

튜플 라벨링 혼합 지원

더 쉬운 배열에 대한 유니온 타입의 메소드 사용

기존 타입스크립트에서 배열에 대한 타입을 여러가지 방식으로 구현이 가능했습니다. 하지만, 배열을 유니온으로 하는 타입에서는 배열 메소드 사용이 불가능 했습니다.

// ✅ Possible declare const arr: (string | number)[]; arr.map((it /* string | number */) => console.log(it)); // ✅ Possible declare const arr2: Array<string | number>; arr2.map((it /* string | number */) => console.log(it)); // ❌ TypeScript Error declare const arr3: string[] | number[]; arr3.map((it /* unknown */) => console.log(it)); // This expression is not callable.
typescript

배열 유니온 타입 오류 예제

기존에는 string[] 과 number[] 의 교집합을 통해 map 을 찾으려 하면서 타입을 찾을 수 없는 문제가 발생하였고, 이번 5.2에서는 (string | number)[] 로 변환하도록 하여, 정상적으로 작동 할 수 있도록 바뀌었습니다.

배열 복사 메서드 추가 지원

ES2023에서 새롭게 추가된 내용으로 배열을 복사하여 사용하는 메서드가 추가되었습니다. 기존 sort, splice, reverse 메서드는 기존의 배열을 바꾸는 객체지향 메서드지만, 이번에 추가된 메서드들은 모두 “복사” 되어 사용되는 메서드입니다.

  • toSorted
  • toSpliced
  • toReversed
  • with
    총 네가지 메서드가 추가되었으며, toSorted, toSpliced, toReversed 세가지 메서드는 기존의 sort, splice, reverse 에 대한 복사 지원 메서드이며, with는 arr[0] = 'some' 처럼 인덱스 대입문에 대한 복사 메서드입니다.
const arr = [2, 4, 6, 1, 3, 5]; _.equal(arr.toSorted(), [1, 2, 3, 4, 5, 6]); _.equal(arr, [2, 4, 6, 1, 3, 5]); const arr2 = [1, 2, 3, 4]; _.equal(arr2.toSpliced(1, 1, 5), [1, 5, 3, 4]); _.equal(arr2, [1, 2, 3, 4]); const arr3 = [1, 2, 3]; _.equal(arr3.toReverse(), [3, 2, 1]); _.equal(arr3, [1, 2, 3]); const arr4 = [1, 2, 3, 4]; _.equal(arr4.with(1, 5), [1, 5, 3, 4]); _.equal(arr4, [1, 2, 3, 4]);
typescript

배열 복사 메서드

WeakMap, WeakSet에서 심볼 키 허용

ES2023에서 적용된 내용으로, WeakMap, WeakSet 의 키 값으로 심볼을 사용할 수 있도록 변경된 내용입니다.

const myWeakMap = new WeakMap(); const key = Symbol(); const someObject = { /*...*/ }; // Works! ✅ myWeakMap.set(key, someObject); myWeakMap.has(key);
typescript

.ts 확장자에 대해 타입 임포트 허용

타입만 임포트하는 import type { ... } from 'file.d.ts' 구문을 통해 불러오는 파일의 확장자는 기본적으로 .d.ts 로 타입 구현 파일입니다. 하지만 allowImportingTsExtensions 옵션을 사용하면 .ts, .mts, .cts, .tsx 에 대해 허용할 수 있지만, 이는 이 옵션의 원래 의미와는 상관없는 내용입니다. 따라서 이제 5.2에서부터는 해당 옵션과 무관하게 허용하도록 변경되었습니다.


그 밖에 VSCode에서 매개변수 힌트에 대해 이름을 클릭하면 구현체로 넘어갈 수 있도록 하는 변경 사항이 있습니다. 관련 내용은 타입스크립트 블로그의 내용을 확인하시면 되고, 관련되어 5.3 버전에 대한 배포 계획도 새롭게 올라왔으니 확인해보시면 좋을거 같습니다. 😃

 

TypeScript 5.2 업데이트

    GitHub - tc39/proposal-symbols-as-weakmap-keys: Permit Symbols as keys in WeakMaps, entries in WeakSets and WeakRefs, and registered in FinalizationRegistries

    Permit Symbols as keys in WeakMaps, entries in WeakSets and WeakRefs, and registered in FinalizationRegistries - tc39/proposal-symbols-as-weakmap-keys

    GitHub - tc39/proposal-symbols-as-weakmap-keys: Permit Symbols as keys in WeakMaps, entries in WeakSets and WeakRefs, and registered in FinalizationRegistrieshttps://github.com/tc39/proposal-symbols-as-weakmap-keys

    GitHub - tc39/proposal-symbols-as-weakmap-keys: Permit Symbols as keys in WeakMaps, entries in WeakSets and WeakRefs, and registered in FinalizationRegistries

    Typescript의 새로운 키워드 “using”

    타입스크립트는 현재 5.1 입니다. 그리고 준비중인 다음 버전인 5.2에서 using 이라는 새로운 키워드가 지원될 예정입니다. 이 키워드는 tc39에 제안된 내용이고, 현재 Stage 3 단계로 다음 ECMAScript에서도 볼 수 있는 후보 상태입니다. 새로운 키워드는 기존 let, const 변수 선언 키워드에 기능이 추가된 형태이며, 이 키워드를 이용해 선언한 변수는 블록 스코프를 벗어날 때 자동으로 자원을 해제해 주는 새로운 기능입니다. 일반적인 자원 해제 코드 패턴 위 예제처럼 스트림, 버퍼 등 다양한 자원의 수명관리와 관련된 소프트웨어 개발 패턴이 존재하고, 다음과 같이 각 상황에 맞게 자원을 해제하는 메서드 호출이 필요합니다. ECMAScript의 Iterator: iterator.return() WHATWG의 Stream Reader: reader.releaseLock() NodeJS의 파일 핸들러: handle.close() Emscripten C++의 객체 핸들: Module.\_free(ptr), obj.delete(), Module.destroy(obj) 또한 throw 를 대응하기 위해 try { ... } finally { ...release }로 오류를 검사하는 것이 일반적입니다. 이는 코드가 길어지고, 반복적인 패턴이고, 개발자가 자원을 해제하지 못할 경우 메모리 누수로도 이어지는 좋지 않은 패턴이기도 합니다. 여러개의 자원을 다루는 코드

    https://opnay.com/p/1311e9ae-0913-4ddd-bd5c-b2af67065bc0

    Typescript의 새로운 키워드 “using”

    GitHub - tc39/proposal-explicit-resource-management: ECMAScript Explicit Resource Management

    ECMAScript Explicit Resource Management. Contribute to tc39/proposal-explicit-resource-management development by creating an account on GitHub.

    GitHub - tc39/proposal-explicit-resource-management: ECMAScript Explicit Resource Managementhttps://github.com/tc39/proposal-explicit-resource-management

    GitHub - tc39/proposal-explicit-resource-management: ECMAScript Explicit Resource Management

    GitHub - tc39/proposal-change-array-by-copy: Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change.

    Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change. - tc39/proposal-change-array-by-copy

    GitHub - tc39/proposal-change-array-by-copy: Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change.https://github.com/tc39/proposal-change-array-by-copy

    GitHub - tc39/proposal-change-array-by-copy: Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change.

    GitHub - tc39/proposal-decorator-metadata

    Contribute to tc39/proposal-decorator-metadata development by creating an account on GitHub.

    GitHub - tc39/proposal-decorator-metadatahttps://github.com/tc39/proposal-decorator-metadata

    GitHub - tc39/proposal-decorator-metadata

    TypeScript 5.3 Iteration Plan · Issue #55486 · microsoft/TypeScript

    This document outlines our focused tasks for TypeScript 5.3. It minimally indicates intent to investigate tasks or contribute to an implementation. Nothing is set in stone, but we will strive to complete these tasks in a reasonable timef...

    TypeScript 5.3 Iteration Plan · Issue #55486 · microsoft/TypeScripthttps://github.com/microsoft/TypeScript/issues/55486

    TypeScript 5.3 Iteration Plan · Issue #55486 · microsoft/TypeScript

    Announcing TypeScript 5.2 - TypeScript

    Today we’re excited to announce the release of TypeScript 5.2! If you’re not familiar with TypeScript, it’s a language that builds on top of JavaScript by making it possible to declare and describe types. Writing types in our code allows us to explain intent and have other tools check our code to catch mistakes like […]

    Announcing TypeScript 5.2 - TypeScripthttps://devblogs.microsoft.com/typescript/announcing-typescript-5-2

    Announcing TypeScript 5.2 - TypeScript

    ES2023 살펴보기

    올해 확정된 ECMA 2023은 총 4가지 제안이 수락되어 적용되었고, 배열에 대한 제안 2가지, 해시뱅, WeakMap 으로 프론트엔드 개발자가 알아두면 좋은 제안은 총 3가지 입니다. 전체 내용을 정리하면서 어떤 기능들이 추가됐는지 확인해봅시다. 마지막 기준 배열 찾기 배열과 형식화 배열(Typed Array)에 새로운 찾기 메서드가 추가되었습니다. Array.prototype.findLast, Array.prototype.findLastIndex 두가지로, 배열의 마지막부터 시작해 찾게되는 메서드입니다. 기존에 있던 find, findIndex 메서드는 모두 함수를 받고 있어 이 스펙을 직접 구현하는건 가능했지만, 함수의 명확한 명명 및 사용을 위해 이같은 제안이 생겼다고 합니다. Array.prototype.findLastIndex 예제 Array.prototype.findLast 예제   복사하여 배열 변경 기존 JS에는 배열에 대한 다양한 메서드가 존재합니다. sort, map, concat, splice 등 사용되는 메서드가 많은데 이들에겐 문제점이 존재합니다. 각 메서드는 리턴되는 값이 다르고, 원본 배열을 수정하는 메서드도 존재합니다. 이는 불규칙적이며, 혼란을 야기하기도 합니다. 원본 배열을 수정하는 메서드들을 수정하지 않고, 새로운 배열을 이용해 메서드를 사용할 수 있도록 새로운 매서드가 추가되었습니다. Array.prototype.toReversed 이 메서드는 기존에 있던 Array.prototype.reverse 라는 메서드의 복사 메서드입니다. 사용 방법을 기존과 동일합니다.

    https://opnay.com/p/28f23ba5-ced5-4610-8306-9f1d8bc6f6cd

    ES2023 살펴보기

    ES2023 살펴보기

    올해 확정된 ECMA 2023은 총 4가지 제안이 수락되어 적용되었고, 배열에 대한 제안 2가지, 해시뱅, WeakMap 으로 프론트엔드 개발자가 알아두면 좋은 제안은 총 3가지 입니다. 전체 내용을 정리하면서 어떤 기능들이 추가됐는지 확인해봅시다. 마지막 기준 배열 찾기 배열과 형식화 배열(Typed Array)에 새로운 찾기 메서드가 추가되었습니다. Array.prototype.findLast, Array.prototype.findLastIndex 두가지로, 배열의 마지막부터 시작해 찾게되는 메서드입니다. 기존에 있던 find, findIndex 메서드는 모두 함수를 받고 있어 이 스펙을 직접 구현하는건 가능했지만, 함수의 명확한 명명 및 사용을 위해 이같은 제안이 생겼다고 합니다. Array.prototype.findLastIndex 예제 Array.prototype.findLast 예제   복사하여 배열 변경 기존 JS에는 배열에 대한 다양한 메서드가 존재합니다. sort, map, concat, splice 등 사용되는 메서드가 많은데 이들에겐 문제점이 존재합니다. 각 메서드는 리턴되는 값이 다르고, 원본 배열을 수정하는 메서드도 존재합니다. 이는 불규칙적이며, 혼란을 야기하기도 합니다. 원본 배열을 수정하는 메서드들을 수정하지 않고, 새로운 배열을 이용해 메서드를 사용할 수 있도록 새로운 매서드가 추가되었습니다. Array.prototype.toReversed 이 메서드는 기존에 있던 Array.prototype.reverse 라는 메서드의 복사 메서드입니다. 사용 방법을 기존과 동일합니다.

    https://opnay.com/p/28f23ba5-ced5-4610-8306-9f1d8bc6f6cd

    ES2023 살펴보기