TypeScript 빙산 #1

TypeScript/src에서 타입 정의 까보기

Table Of Contents

들어가기

이 그림을 본 적이 있나요?

TypeScript Iceberg

나는 이 그림을 본 지 벌써 1년이 넘어 가는 것 같은데... 위쪽에 위치한 키워드들도 아직 정확히 설명할 수 없는 것들이 있다.

그래서 오늘부터 하나씩 차근차근 포스팅해보려 한다.

string / boolean

any

unknown

Array<T>

Class

Class는 JS의 문법으로, 객체를 생성하기 위한 템플릿이다.

Class 선언을 이용하여 Class를 정의하는 과정에서 type을 입히는 예시는 아래와 같다.

class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } }

Error

Error는 JS의 표준 내장 객체 중 하나다. 런타임 에러가 발생하면 JS에서는 Error 객체를 만들어 돌려준다.

TS에서는 이 객체를 다루기 위해 TS에 Error 타입을 정의해서, 우리는 기본적으로 Error 타입을 사용할 수 있다.

TypeScript/src/lib/es5.d.ts 파일 내에서 아래와 같은 기본적인 Error 타입 정의를 찾아볼 수 있다.

interface Error { name: string; message: string; stack?: string; }

추가로, es2022에서는 Error 클래스에 cause 속성이 추가되었다. 이에 맞춰서 TypeScript에서도 TypeScript/src/lib/es2022.error.d.ts 파일 안에 아래와 같은 interface 선언을 추가해 타입을 확장했다.

interface Error { cause?: unknown; }

cf) TypeScript에서는 같은 이름으로 interface를 여러 번 선언하면, 선언 병합(Declaration Merging) 이 일어나 각 선언이 하나의 interface로 합쳐진다. 따라서 이렇게 다른 파일에서 같은 이름으로 각각 인터페이스를 선언해 확장할 수 있다.

Date

interface Date { /** Returns a string representation of a date. The format of the string depends on the locale. */ toString(): string; /** Returns a date as a string value. */ toDateString(): string; /** Returns a time as a string value. */ toTimeString(): string; ... 후략 }

Promise<string>

Promise 역시 JS의 표준 내장 객체 중 하나로, 비동기 작업이 맞이할 미래의 완료 도는 실패와 그 결과값을 나타낸다.

여기에서도 Generic이 사용되었다.

살짝 설명하자면... Promise는 원래 비동기 작업의 결과를 나타낸다고 위에서 말했는데, 이 결과값의 타입을 <string> 부분을 이용해서 선언해주고 있는 것이다.

그래서 TypeScript/src/lib/es5.d.ts에 정의된 Promise의 타입 선언을 보면, Generic을 사용해 Promise<T>처럼 사용하고 있다. 즉, Promise가 처리할 값의 타입을 T로 둔다는 뜻이다.

interface Promise<T> { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ then<TResult1 = T, TResult2 = never>( onfulfilled?: | ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: | ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null ): Promise<TResult1 | TResult2>; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ catch<TResult = never>( onrejected?: | ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null ): Promise<T | TResult>; }

BigInt

위에서 JS의 원시 값(primitive) 중 bigint가 있다고 했다. 따라서 TS에서도 bigint(소문자다!) 타입이 존재한다.

그런데 여기에서는 BigInt를 언급했으므로, JS의 표준 내장 객체 중 하나인 BigInt(대문자에 주의)를 가리키는 것 같다.

BigIntNumber가 나타낼 수 있는 최대치인

2^{53} - 1
보다 큰 정수를 표현할 수 있는 내장 객체이다.

따라서 TS에서는 BigInt를 다루기 위해 타입을 따로 선언해 두었는데, BigInt는 es2020부터 도입되었으므로 TypeScript/src/lib/es2020.bigint.d.ts에서 타입 선언을 찾아볼 수 있다.

interface BigInt { /** * Returns a string representation of an object. * @param radix Specifies a radix for converting numeric values to strings. */ toString(radix?: number): string; /** Returns a string representation appropriate to the host environment's current locale. */ toLocaleString( locales?: Intl.LocalesArgument, options?: BigIntToLocaleStringOptions ): string; /** Returns the primitive value of the specified object. */ valueOf(): bigint; readonly [Symbol.toStringTag]: "BigInt"; }

(string | boolean)[]

참고