본문 바로가기

IT/typescript34

[Typescript] Branded type 개념 값이 사용되기 전에 특정 기준을 충족하는 지 확인함으로써 컴파일 오류를 발생시켜 조기에 파악하는 데 도움이 됨 입력의 유효성을 검사하는 Assertion 함수와 같이 사용할 때 유용 생성 방법 기존 타입에 readonly 속성을 추가한다. 보통 readonly 속성은 '__brand', '__kind', '__type' 으로 이름 짓는다. type PositiveNumber = number & { __brand: 'PositiveNumber' }; function divide(a: number, b: PositiveNumber) { return a / b; } const x: PositiveNumber = 10; // Error: 'number' is not assignable to 'Positiv.. 2024. 2. 21.
[Typescript] asserts를 이용한 타입 가드 활용 asserts 활용 (v3.7부터 가능) function assert(value: any, errorMsg: string): asserts value { if(!value) throw new Error(errorMsg) } function toString(value? : number) { assert(value !== undefined, 'value should not be undefined') return value.toFixed(2) } console.log(toString(4), typeof toString(4)) // "4.00", "string" https://fe-developers.kakaoent.com/ 홈 | 카카오엔터테인먼트 FE 기술블로그 fe-developers.kakaoent.com 2024. 2. 5.
[Typescript] 외부 패키지의 타입 치환 한번 감싸기 // asis const toast = useSelector((state: MyState) => state.common.toast) // tobe export default function useTypedSelector(selector: (state: MyState) => R): R { return useSelector(selector) } 타입 치환 interface DefaultMyState { common: {...} } declare module 'react-redux' { interface DefaultRootState extends DefaultMyState {} } https://fe-developers.kakaoent.com/ 2024. 2. 5.
[Typescript] index signature vs mapped type 결론 mapped type 추천 이유 컴파일 시 에러가 발생하기 때문에 실수를 예방할 수 있음 type Fruite = 'Banana' | 'Apple' | 'Orange' const PriceMap: {[fruit:string]:number} = { Apple: 1000, Banana: 1000, Orange: 2000, } const PriceMap2: {[fruit in Fruite]:number} = { Apple: 1000, Banana: 1000, Orange: 2000, } function getDiscountedPrice(fruit: string, discount: number) { return PriceMap[fruit] - discount } const a = getDiscountedP.. 2024. 2. 5.
[Typescript] enum vs union 결론 enum 보다는 union type 이유 컴파일 해보면 객체가 생성됨 > typescript 사용 이유가 정적 타입을 사용하기 위함인데, 정적 타입 정보가 런다음에 영향을 준다는 사실이 썩 내키지 않는다. > const enum을 사용해도 되지만, import 구문이 추가됨 enum Fruite { Banana, Apple, Orange } complied "use strict"; var Fruite; (function (Fruite) { Fruite[Fruite["Banana"] = 0] = "Banana"; Fruite[Fruite["Apple"] = 1] = "Apple"; Fruite[Fruite["Orange"] = 2] = "Orange"; })(Fruite || (Fruite = {}).. 2024. 2. 5.
TS - 5.0 New features Decorators 실험적인 기능으로 제공되었었지만, ECMAScript (Stage 3) 스펙에 맞게 업데이트 됨 개념 class, method, accessor, property, parameter에 함수를 붙여 기능을 확장하는 함수 차이점 decorator 함수를 만들 때 기존과 다른 파라미터를 넘겨 받는다. 5.0으로 마이그레이션을 해야한다면 꼭 유의해야 한다. nestjs에서 TS 5.0을 지원하는지 확인해야겠죠? // v4.9.5 function loggedMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor){ console.log("target: ", target); console.log("propertyKey: ".. 2023. 7. 1.