TIL

타입스크립트에서 상수를 안전하게 쓰는 법

1. as const

객체 리터럴이나 배열의 내부 프로퍼티에 접근하는 것을 막아준다. 접근하면 에러!

Readonly<T>, ReadonlyArray<T> 같은 것도 똑같은 역할을 해준다.

https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#readonly-and-const

 

Documentation - TypeScript for Functional Programmers

Learn TypeScript if you have a background in functional programming

www.typescriptlang.org

2. type typeof keyof

typeof, keyof 모두 타입을 반환한다. typeof는 객체의 타입을 반환하지만 keyof는 객체의 키타입을 반환한다는 차이점이 있다.

https://www.typescriptlang.org/docs/handbook/2/types-from-types.html#handbook-content

 

Documentation - Creating Types from Types

An overview of the ways in which you can create more types from existing types.

www.typescriptlang.org

 

3. user-defined type guards (사실 이것 때문에 글을 썼다.)

런타임에 타입마다 실행하는 메서드를 다르게 하고 싶다던가 하는 등의 직접적인 타입 제어를 하고 싶다면  type predicates 를 사용해보는 것도 좋다.

나는 대충 이런 식으로 사용했다. 물론 CUST_GRADE_TYPE이 있긴 하지만 이건 정적으로만 의도한 대로 사용할 수 있기 때문에 따로 런타임에 체크할 수 있는 메서드를 만들었다.

This is Type 이게 정확히 어떤 역할을 해주는지는 좀 더 봐야할 것 같다.

export function isCustGrade(
	gread: CUST_GRADE_TYPE | string | undefined
): grade is CUST_GRADE_TYPE{
	return (
    	grade === CUST_GRADE.VIP ||
        grade === CUST_GRADE.GREEN ||
        grade === CUST_GRADE.YELLOW
    )
 }

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

 

Documentation - Narrowing

Understand how TypeScript uses JavaScript knowledge to reduce the amount of type syntax in your projects.

www.typescriptlang.org