본문 바로가기

IT/typescript31

[Typescript] Type-Only Imports and Export 개념 타입 표기와 선언에 사용될 선언만 import 한다. 완전히 제거되므로, 런타임에 남아 있는 것은 없다. import type { mapboxgl } from './mapboxgl' export type { mapboxgl } 특징 클래스는 런타임에 값을 가지고, 디자인-타임에 타입을 있으며 사용은 상황에 따라 다를 수 있다. import type을 사용하면, 확장 같은 것은 할 수 없다. import type { Component } from "react"; interface ButtonProps { // ... } class Button extends Component { // ~~~~~~~~~ // error! 'Component' only refers to a type, but is bein.. 2024. 3. 8.
[Typescript] satisfies 배경 개발자들은 딜레마에 빠진다. 개발 하다보면 object의 맴버들이 type에 매칭되길 원할 뿐만 아니라 타입추론으로 인하여 가장 명확한 타입을 유지하기 원한다. 상황 예 const palette = { red: [255, 0, 0], green: '#00ff00', bule: [0,0, 0] //^^^^ typo } const redComponent = palette.red.at(0) const greenNormalized = palette.green.toUpperCase() 기존 시도 object에 type 선언했더니 로직에서 에러 발생 type Colors = 'red' | 'green' | 'blue' type RGB = [red: number, green: number, blue: numbe.. 2024. 2. 22.
[Typescript] 타입 호환성 Typescript의 타입 호환성 > 구조적 서브타이핑 기반 구조적 서브타이핑 > 오직 멤버만으로 타입을 관계시키는 방식 > y가 최소환 x와 동일한 멤버를 가지고 있다면, x와 y는 호환된다. > '덕 타이핑'이라고도 함 '만약 어떤 새가 오리처럼 걷고, 헤엄치고, 꽥꽥거리는 소리를 낸다면 나는 그 새를 오리라고 부를것이다' type Food = { /** 각 영양소에 대한 gram 중량값 */ protein: number; carbohydrates: number; fat: number; } type Burger = Food & { /** 햄버거 브랜드 이름 */ burgerBrand: string; } function calculateCalorie(food: Food) { return food.pro.. 2024. 2. 22.
[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.