관리 메뉴

Silver Library (Archived)

뭘 놓쳤을까? - Typescript, uuid, useState 본문

Face the fear, build the future/Revision Sector

뭘 놓쳤을까? - Typescript, uuid, useState

Chesed Kim 2022. 6. 2. 22:33
반응형

TS로 일정표를 만들기 위해 필요한 것은, 크게 두갈래길로 보인다.

 

하나는, useState 를 사용하고, FC 를 선언 해 주면서 시작하는 것.

FC , the component automatically accepts children provided to your component. It will not throw any typescript error, but it actually should, because the children do nothing.

나머지는, 비록 멋은 없어 보이지만 가장 친숙한 JS 위주의 표현식으로 진행하는 것.

예를 들면, 아래의 코드처럼 말이다.

import { v4 as uuidV4 } from "uuid"

type Task = {
  id: string
  title: string
  completed: boolean
  createdAt: Date
}

const list = document.querySelector<HTMLUListElement>("#list")
const form = document.getElementById("task") as HTMLFormElement | null
const input = document.querySelector<HTMLInputElement>("#task-title")
const tasks: Task[] = loadTasks()
tasks.forEach(addListItem)

form?.addEventListener("submit", e => {
  e.preventDefault()

  if (input?.value == "" || input?.value == null) return
  
  const newTask: Task = {
    id: uuidV4(),
    title: input.value,
    completed: false,
    createdAt: new Date()
  }
  tasks.push(newTask)

  addListItem(newTask)
  input.value = ""
})

여담으로, type 이나 interface 나 상관 없지만, 추가로 병합 해서 사용 할 생각이라면 interface 가 적합하다.

아래처럼 할 경우, interface 만이 가능하고 type은 이게 불가하다.

interface Window {
  title: string;
}

interface Window {
  ts: import("typescript");
}

declare function getWindow(): Window;

const window = getWindow();
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});

자, 그럼 이제 대망의 일정표 작성에 필요한 것은 무엇일까?

일단은 기초부터라고, 가장 익숙한 JS 표현식으로 먼저 접근 해 보기로 했다.