Typescript

Typescript

재귀로 객체 내 모든 키값을 추출하는 타입 만들기

재귀로 객체 내 모든 키값을 추출하는 타입 만들기 객체 내 모든 키를 추출할 수 있는 타입을 만든 후, 컴포넌트에 적용하여 컴포넌트가 props로 받는 객체의 타입을 스스로 추론하게 만들어보자. 객체 재귀 타입(PropertyPath) 구현 type PropertyPath = U['length'] extends 10 ? never : { [K in keyof T & string]: T[K] extends Record ? K | `${K}.${PropertyPath}` : K }[keyof T & string] 위의 PropertyPath 타입은 객체의 모든 키를 추출하는 타입이다. 원활한 이해를 위해 몇가지 사전 ..

Typescript

객체 키 타입의 유니온 추출 및 활용

객체 키 타입의 유니온 추출 및 활용 상수로 이용하려는 이미 정의된 객체 데이터를 타입스크립트로 다루다보면 가끔씩 불편한 상황을 마주하곤 한다. 나의 경우에는 객체 데이터 자체를 타입으로써 이용하고 싶은데 타입스크립트가 너무 빡빡하게 굴 때 종종 심기가 불편해진다. 가끔은 객체 타입을 모두 손수 지정해버리고 싶다는 충동이 들 때마저 있다. 물론 왕도는 없는듯 하다. 유지보수가 다소 어려워질것을 감안하고 객체의 타입을 모두 손수 지정해서 사용할 것인지, 아니면 특정 객체를 100% 신뢰한 상태에서 타입을 뻗어낼 것인지는 상황에 따라 판단하면 된다. 하지만 두 방법 모두 잘 알고 있기는 해야할 것이다. 객체 타입을 모두 손수 지정하는 것은 어렵지않은 단순 노가다이므로, 이 글에서는 객체 타입을 프로퍼티로 각..

Typescript

유틸리티 타입 (Parameters)

Parameters 함수의 파라미터를 타입으로 만드는 유틸리티 타입이며, 특정 함수의 파라미터를 튜플로 반환한다. 특정 컴포넌트의 파라미터를 타입으로 뽑아낼 때 유용하다. 객체지향 설계 중 리스코프 치환의 원칙을 구현할 때 적극적으로 사용할 수 있을 것 같다. function testFn({str, num, arr}: {str: string, num:number, arr: T[] }, context: string) { return { str, num, arr } } type TestParameter = Parameters[0] const shadow = ({ str, num, arr }: TestParameter) => { return str }

Typescript

유틸리티 타입 (Partial, Required, Record)

https://www.typescriptlang.org/ko/docs/handbook/utility-types.html#excludetype-excludedunion Documentation - Utility Types Types which are globally included in TypeScript www.typescriptlang.org Partial // Partial type Post = { title: 'string' index: number content: string } const updatePostContent = (post:Post, updateContent: Partial):Post => { return {...post, ...updateContent} } Partial은 Type의..

Typescript

keyof typeof typesomething

이런게 되는구나 싶네요. type CalculatorProps = { left: number operator: keyof typeof operations right: number } type operations = { '+': (left: number, right: number) => number '-': (left: number, right: number) => number '*': (left: number, right: number) => number '/': (left: number, right: number) => number } operations 타입의 모든 key를 뽑아 CalculatorProps.operator의 유니온 타입으로 적용합니다.

Typescript

React 컴포넌트에 타입스크립트 적용

https://kentcdodds.com/blog/how-to-write-a-react-component-in-typescript How to write a React Component in TypeScript Stay up to date Subscribe to the newsletter to stay up to date with articles, courses and much more! Learn more Stay up to date Subscribe to the newsletter to stay up to date with articles, courses and much more! Learn more All rights reserved © Kent C. D kentcdodds.com 위 글을 참고했습..

Typescript

catch문의 error 타입이 any 또는 unknown여야 하는 이유

Catch clause variable type annotation must be 'any' or 'unknown' if specified. 캐치문의 error 타입은 왜 any와 unknown이어야 하는 걸까? 개발하다가 아래와 같은 타입 에러를 만났다. 왜 캐치문의 에러는 any, unknown이어야 하는 걸까? https://stackoverflow.com/questions/69021040/why-catch-clause-variable-type-annotation-must-be-any Why Catch clause variable type annotation must be any? I'm using yup to validate a form, and I encountered this type erro..

Typescript

함수 표현식에 타입 적용하기

함수 표현식과 타입 할당 자바스크립트에서 함수는 표현식으로 나타낼 수 있다. 함수 타입을 만들고, 함수 표현식에 타입을 할당하면 함수에 타입을 깔끔하게 명시할 수 있다. type DiceRollFn = (sides:number) => number const rollDice: DiceRollFn = (sides) => { return sides } const rollDiceAndPlusOne: DiceRollFn = (sides) => { return sides + 1 } 다른 함수의 타입 참조 : typeof fn 다른 함수의 타입을 그대로 참조하기 위해 typeof fn를 사용할 수 있다. 타입에서의 typeof는 별도의 값을 산출하는 연산자가 아님을 기억하자. declare function fetch..

Typescript

타입 단언과 타입 선언 사용 시기

타입 단언, 타입 선언 interface Person {name: string}; const alice: Person = { name: 'Alice' } // Person 타입 (타입 선언) const alice = { name : 'Alice' } as Person // Person 타입 (타입 단언) 두 가지 방법은 결과가 같아보이지만 그렇지 않다. 첫 번째 방법은 변수에 타입을 붙여 타입을 선언한 것이고, 두번째는 as Person으로써 타입을 단언한 것이다. 타입 선언은 타입 체커가 동작한다. const alice: Person = {}; // -- 타입 에러 const bob = {} as Person; // 오류 없음 타입 선언은 할당되는 값이 해당 인터페이스를 만족하는지 검사한다. 앞의 예제..

Typescript

(TS) TodoList 작성과, interface, type assert에 대한 내 생각

HTML Click Me TS interface Todo { text: string, completed: boolean } const btn = document.getElementById("btn") as HTMLButtonElement const input = document.getElementById("todoinput") as HTMLInputElement const form = document.querySelector("#todoform") as HTMLFormElement const list = document.querySelector("#todoList") as HTMLUListElement const readTodos = (): Todo[] => { const todosJSON = local..

2DC
'Typescript' 카테고리의 글 목록