📁
til
  • TIL(Today I Learned)
  • javascript
    • value-number-string-boolean-null-undefined
    • primitive-reference
    • Hoisting
    • Prototypes in Javascript
    • this
    • prototype
    • 콜백함수 (Callback function)
    • 함수의 호출
    • 자료구조 new keyword
    • closure
    • Promise
    • event-loop
    • array-object
    • 객체
    • Arguments
    • higher order function
    • operators-function-control-flow
    • 객체 생성 패턴 3가지
    • Javascript scopes
    • Functional Programming
    • Design Patterns
    • 데이터 타입
    • Object 객체
    • 표준 내장 객체의 확장
    • 참조
    • 함수
    • 상속(Inheritance)
    • this - 'this'를 사용하는 해당 함수를 '어떻게' 실행하느냐에 따른 4가지 this 정의
    • 전역객체(Global object)
    • 객체 지향 프로그래밍
    • The 'new' keyword - Object Creation in JavaScript
  • javascript-api
    • Number
      • Number.MAX_VALUE
      • Number.isInteger
      • Number.NEGATIVE_INFINITY
      • Number.isNaN()
      • Number.POSITIVE_INFINITY
      • Number.parseFloat
      • Number.EPSILON
      • number.toExponential
      • Number.MAX_SAFE_INTEGER
      • Number1 - 자연수, 정수, 10진수, 2진수, 부동소수점, 실수
      • Number.isSafeInteger()
      • Number.MIN_VALUE
      • Number.parseInt
      • Number.NaN
      • Number.isFinite()
      • Number.MIN_SAFE_INTEGER
      • toFixed
    • string.split
    • String.fromCodePoint
    • string.trimEnd
    • string.padStart
    • string.@@iterator
    • String.fromCharCode
    • string.toUpperCase
    • string.codePointAt
    • string.toLowerCase()
    • string.toString
    • string.includes
    • string.replace()
    • string.charAt
    • String.lastIndexOf
    • string.slice
    • string.search
    • string.padEnd
    • string.substring
    • string.length
    • string.trim
    • string.localeCompare
    • String.indexOf
    • string.endsWith
    • string.valueOf
    • String.raw
    • string.matchAll()
    • string.repeat
    • string.match
    • String.prototype
    • string.startsWith
    • string.charCodeAt
    • string.trimStart
    • string.concat
    • string.toLocaleUpperCase()
    • string.toLocaleLowerCase
    • String
  • learn-node
    • debugger
    • Tip
  • schema-design
    • Database Schema Design
    • Database Schema Design
  • react
    • LifeCycle
    • redux
    • Context API
    • 함수형 컴포넌트와 클래스, 어떤 차이가 존재할까?
    • Hooks과 useEffect 사용해 보기
    • Route
    • async wait 사용하기
    • Hooks API Reference
    • context
    • npm uninstall 하는법
    • test 만들기
  • tip
    • 클린코드
    • BxSlider로 텍스트 흐르는 효과 만들기
  • javascript30
    • Event Capture, Propagation, Bubbling and Once
    • Object and Arrays - Reference VS Copy
  • typescript
    • 우아한 타입스크립트 2부
    • The Basic Cheatsheet
    • TypeScript
    • Type Guards and Differnetiating Types
    • 우아한 타입스크립트
    • Generics
  • git-from-the-hell
    • git
    • init-status-add-commit-log-stage-repository
    • log-diff
    • 머지 후 branch 삭제하기
    • 지옥에서 온 Git
    • reset-revert
    • develop branch 를 pull 하고 싶을때
  • conference-and-seminar
    • 모던 프론트엔드 개발환경의 이해
  • fire-base
    • Firebase .gitignore
  • vanillacoding
    • Data Structures
    • Sorting Algorithms - part 1
    • Promise
    • class
    • 04.quiz
    • 07.event-loop
    • Design Patterns
    • OOP (Object Oriented Programming)
  • etc
    • 알고리즘 코드리뷰
    • 스스로 공부하는 법
    • 바닐라코딩 수강 후기
    • async 과제 후기 - 비동기, 동기, 클로저, 배열과 객체
    • 유용한 사이트
  • algorithm
    • The Supermarket Queue
    • Find the odd int
    • The Office III - Broken Photocopier
    • Directions Reduction
    • The Office II - Boredom Score
    • Divisible Sum Pairs
    • Codewars 이용자 솔루션 모음
    • Shortest Word
    • find key
    • Two Sum
    • Simple Pig Latin
  • Book
    • the essence of object-orientation
      • 타입과 추상화
      • 객체 지도
      • 이상한 나라의 객체
      • 추상화 기법
      • 05. 책임과 메시지
      • 07.함께 모으기
      • 04. 역할, 책임, 협력
      • 협력하는 객체들의 공동체
  • ecma-script2015
    • Object Literal Upgrades
    • default-parameter-template-literals-arrow-functions
    • spread-operator-rest-param
    • let-const-rest-parameter-spread-operator-destructuring
  • http
    • 웹 브라우저에 URL을 입력했을 때 어떻게 웹 페이지가 보여질까?
  • jest
    • toThrow(error?)
  • data-structures
    • Data Structures
  • express
    • express generator
    • CORS
  • css-flexible-box-layout
    • flex 해버렸지 뭐야
  • git
    • Git
  • mongodb
    • MongoDB
  • markdown
    • use-markdown
  • cmder
    • cmd 명령어 모음
  • debug
    • trackClicksEx function error
  • npm
    • NPM TOKEN 설정하기
  • storybook
    • Storybook
  • sort
    • Sorting Algorithms - part 1
  • javascript-koans
    • Javascript Koans 오답노트
  • rxjs
    • Rx.js
  • dom-elements
    • HTML Element
  • redux-toolkit
    • Redux Toolkit
  • github-actions
    • GitHub Actions
  • redux-middleware
    • redux middleware
  • rest
    • rest
  • css-rendering
    • 코드 스피츠 - CSS Rendering 1회차 2/2
    • 코드 스피츠 - CSS Rendering 1회차 1/2
  • you-dont-know-js
    • 타입
  • server
    • # shutdown local server
  • semantic-versioning
    • Semantic Versioning 2.0.0
Powered by GitBook
On this page
  • 전제 조건
  • Function Components
  • Hooks

Was this helpful?

  1. typescript

The Basic Cheatsheet

전제 조건

전제 조건을 보면서 알게 된 사실 정리

TypeScript의 장점

  1. TypeScript를 쓴다면 JavaScript에서 unit test를 쓸 필요가 없다. TypeScript가 자동적으로 체크해 준다.

  2. This is especially useful when you’re using a UI library and need to transform data. For example, if you’re using React, you’ll need to transform data in state updates.

we can use mapped types like Readonly to convert one type to another type.

   // Readonly<...> makes each property readonly
   type Todo = Readonly<{
     id: number
     text: string
     done: boolean
   }>

   // 위 <...>은 아래와 같다.
   type Todo = {
     readonly id: number
     readonly text: string
     readonly done: boolean
   }

readonly는 array의 push와도 같이 쓰일 수 있다.

Type assertions

let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// as Type을 더 추천한다.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

Function Components

Hooks

useState

const [user, setUser] = React.useState<IUser | null>(null);

default value인 null과 함께 |를 사용하는 union type을 많은 hook들은 사용한다.

useRef

initial value가 없는 ref container 생성할 때

const ref1 = useRef<HTMLElement>(null!);
const ref2 = useRef<HTMLElement | null>(null);
  • ref1는 readonly용 react가 관리할 built-in ref attributes에 전달하기 위한 것? (Response handles for your current value setting)

  • ref2는 ref2.current를 mutable하게 해주고 사용자가 직접관리하는 instance variables 를 위한 것이다.

네? 뭐라구여???

useEffect

함수 또는 undefined 이외에 다른 것이 return 되지 않도록 주의한다.

setTimeout을 사용하는 경우 number가 return되기 때문에 curly brace로 꼭 감싸자.

useRef

function TextInputWithFocusButton() {
  // 초기값은 null, HTMLInputElement를 찾고 있다고 TypeScript에 말함
  const inputEl = React.useRef<HTMLInputElement>(null);
  const onButtonClick = () => {
    // strict null 체크는 inputEl와 current가 존재하는지 확인해야한다.
    // 존재하면 HTMLInputElement type이므로 따라서 method focus를 가진다. 🙂 Yay
    if (inputEl && inputEl.current) {
      inputEl.current.focus();
    }
  };
  return (
    <>
      {/* 또한 inputEl는 input요소만 사용할 수 있다? focus 때문인가 */}
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

useReducer

type AppState = {};
type Action =
  | { type: "SET_ONE"; payload: string }
  | { type: "SET_TWO"; payload: number };

export function reducer(state: AppState, action: Action): AppState {
  switch (action.type) {
    case "SET_ONE":
      return {
        ...state,
        one: action.payload, // `payload` is string
      };
    case "SET_TWO":
      return {
        ...state,
        two: action.payload, // `payload` is number
      };
    default:
      return state;
  }
}

Discriminated Unions(유니온 식별)은 singleton types, union types, type guards, 및 type aliases을 결합하여 discriminated unions, tagged unions, 또는 algebraic(대수의) data type으로 불리는 고급 패턴을 빌드할 수 있다.

interface Square {
  kind: "square";
  size: number;
}
interface Rectangle {
  kind: "rectangle";
  width: number;
  height: number;
}
interface Circle {
  kind: "circle";
  radius: number;
}

결합할 interface를 선언한다.

공통적으로 kind라는 프로퍼티를 가지고 있는데 이를 discriminant 혹은 tag라고 부른다.

type Shape = Square | Rectangle | Circle;

결합쓰

function area(s: Shape) {
    switch (s.kind) {
        case "square": return s.size * s.size;
        case "rectangle": return s.height * s.width;
        case "circle": return Math.PI * s.radius ** 2;
    }
}

discriminated union을 사용하자!

useReducer에서는 type이 discriminant 혹은 tag가 되는 것이고

이전에 봤던 코드들을 생각하면 App component에서 status 를 예시로 들 수 있을 거 같다.🤭

export interface VerifyingAuth {
  status: 'verifying';
}

export interface UnsignedAuth {
  status: 'unsigned';
  inProgress?: 'signing';
  error?: Error;
}

export interface SignedAuth {
  status: 'signed';
  inProgress?: 'passwordChanging' | 'unsigning';
  error?: Error;
  token: string;
  user: UserInfo;
}
export type Auth = VerifyingAuth | UnsignedAuth | SignedAuth;
<AuthProvider api={api}>
  {(auth: Auth) => {
    switch (auth.status) {
      case 'verifying':
        return <div>...verifying</div>;
      case 'unsigned':
        return (
          <Switch>
            <Route exact path="/" component={LoginPage} />
            <Redirect to="/" />
          </Switch>
        );
      case 'signed':
        return (
          <MissionProvider>
            <Switch>
              <Route path="/dashboard" component={DashboardPage} />
              <Route path="/missions/:missionId" component={MissionPage} />
              <Redirect to="/dashboard" />
            </Switch>
          </MissionProvider>
        );
      default:
        return <div>Unknown auth status...</div>;
    }
  }}
</AuthProvider>

Custom Hooks

Previous우아한 타입스크립트 2부NextTypeScript

Last updated 5 years ago

Was this helpful?

출처

reducer action을 사용한다. return type을 정의하는 것을 절대 잊지말자.

https://ts.chibicode.com/todo/
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L800-L1031
Discriminated Unions