Typescript - useState, props

Jaemin Jung·2022년 1월 20일
0

Typescript

목록 보기
12/13
post-thumbnail

useState에서 타입 지정

  • 기존 React에서 타입 지정
import { useState } from 'react';

const [count, setCount] = useState(0);
  • 타입스크립트에서 타입 지정

import { useState } from 'react';

const [count, setCout] = useState<number>(0);

타입을 미리 지정해놓고 적용도 가능 (type interface 사용)


import { useState } from 'react';

interface todo = {
	id: number;
  	title: string;
  	contents: string;
  	done: boolean
}

interface todos = [ todo ]

const [count, setCout] = useState<todos>([{
	id: 1;
  	title: "learn typescript";
  	contents: "타입스크립트 마스터하기";
  	done: false
}]);

export, import를 이용해 별도의 파일에서 타입 관리 가능

export interface todo = {
	id: number;
  	title: string;
  	contents: string;
  	done: boolean
}

export interface todos = [ todo ]

...

import { todos } = "해당 경로"

const [count, setCout] = useState<todos>([{
	id: 1;
  	title: "learn typescript";
  	contents: "타입스크립트 마스터하기";
  	done: false
}]);

props

타입스크립트는 props에도 타입을 지정해야한다.
props를 받는 컴포넌트에서 타입을 지정 가능하다.
rops로 지정할 수 있는 변수들의 이름과 형태까지 지정해 줄 수 있어서
자식 컴포넌트에 Props를 넘겨줄 때 일어나는 문제점을 미리 방지 할 수 있다.

interface NameProps {
  name: string;
}

const VeiwName = ({name}: NameProps) => {
	return <div>{name}</div>
}

interface 뒤에 props의 이름을 따로 선언해주고 보통 끝에 Props를 붙여준다.

만약에 Lifting State Up을 위해서 Set 함수를 받아올 때 함수 타입을 정의하는 방식은 다음과 같다.

interface NameProps {
	name: string;
  	handleName: (event:React.ChangeEvent<HTMLInputElement>) => void
}

함수의 파라미터 타입과 반환 타입을 정의한다.

interface, type 차이점

  • interface는 객체에만 사용이 가능하다.

  • interface는 선언적 확장이 가능하다.(type은 새로운 속성을 추가하기 위해 중복 선언 불가능)

  • 성능을 위해서는 interface를 사용하는 것이 좋다.

  • 결론
    객체, 그리고 타입간의 합성등을 고려해 보았을 때 interface를 쓰는 것이 더 나을지 않을까 싶다.

profile
내가 보려고 쓰는 블로그

0개의 댓글