본문 바로가기

TypeScript7

[패턴] Discriminating unions - To narrow down the type within a union type = 타입 가드 type LocationState = { state: 'Loading' | 'Success' | 'Error' coordinate?: { lat: number, lan: number } error?: { message: string }}/** state 가 loading 일때는 coordinate 와 error 이 필요없다.* state 가 success 일때는 error 이 필요없다.* state 가 error 일때는 coordinate 가 필요없다.* 위와 같이 옵셔널로 타입을 지정했을때 문제는...*/function printLocation(location: LocationState){ switch(location.state){ .. 2024. 6. 5.
제네릭 Generic // Use casetype ApiResponse = { data: Data isErrpr: boolean}// case#1const response: ApiResonse = { data: { status: 200 }, isError: false}const response: ApiResonse = { data: "abcde", isError: false}// case#2 = 타입의 확장type UserResponse = ApiResponse;type BlogResponse = ApiResponse;const response: UserResponse = { data: { name: 'abcde', age: 1 }, .. 2024. 6. 5.
keyof, typeof, as const 객체의 속성명(key)을 타입으로 사용하고싶을때... const obj = { a: "123", b: "hello", c: "world" }type Key = keyof obj // obj는 "값"이기 때문에 타입으로 타이핑할 수 없기 때문에 오류로 표기된다.const obj = { a: "123", b: "hello", c: "world" }type Key = keyof typeof obj // obj의 키(key)들을 타입으로써 사용가능하다. type Key = "a" | "b" | "c" 와 같다.// USE CASES...// 1type Movie = { id: number; name: string; lengthInMinutes: number;}const titanic: Movie = .. 2022. 9. 28.
useEffect 안에서 useRef 사용 시 타이핑 목적: li 태그 안에 있는 "data-param"의 값을 참조해 state값을 수정. 에러내용: 1. 위와 같이 useRef(null)로 선언 후 useEffect 안에서 dataset.param을 읽으려고 했으나 타입추론이 잘못되어 경고가 나타남. 이유: usRef가 "null" 형식(타입)으로 리턴하기 때문에 dataset의 속성이 없다는 경고 메시지가 나왔다. 시도#1: useRef를 HTML li 요소임을 제네릭으로 타이핑. 결과: 실패 이유: 이번에는 "HTMLLIElement" 형식에서 dataset의 속성이 없다는 경고 메시지가 또 나왔다. useRef로 DOM요소에 접근하기 위해서는 "current" 키를 사용해야 한다. 그래서... 와 같이 선언하니 작동되었다. 사실 any로 타이핑했을.. 2022. 9. 24.
[객체타입] readonly, 인덱스드 시그니처, 맵드 타입스 // 수정할 수 없는 타입 readonlyinterface A { readonly a: string, b: string } type B = { a: string, b: string, c: string, d: string }// 인덱스트 시그니처type C = { [ key: string ]: string }// 맵드 타입스type D = "Human" | "Mamal" | "Animal"type E = { [ key in D ]: string }type Ee = { [ key in D ]: D }const aaa: E = { Human: "a", Mamal: "b", Animal: "c" }const aaa: Ee = { Human: "Human", Mamal: "Mamal", Animal: "Anima.. 2022. 9. 15.
Type guard / narrowing / predicates 타입 가드를 사용하는 이유는 보통 fetch 로 union 타입의 데이터를 가져올때이다. 만약 API 호출로 받아온 데이터의 타입이 string인데 toFixed(n) 과 같은 메서드를 사용했을때 에러를 발생시킨다. 당연히 그 뒤에 오는 코드들도 실행되지 않으니 큰 문제가될 수 있다. 타입가드, 타입 좁히기할때 사용할 수 있는 방법으로는.. ■ Primitive value check- typeof : 원시값(string, number, boolean) 을 체크한다. ■ Reference value check- instanceof : class only ■ Object's key name check- key in obj : 객체에서 key 값이 있는지 확인 ■ Object array check- isArr.. 2022. 9. 13.