리액트 - 타입스크립트

veloger·2024년 3월 13일
0

REACT 리액트

목록 보기
15/15

커스텀 타입 만드는 방법

type 형태

export type A = {
 	name:string;
    age:number;
    address:{
    	city:string;
    	phone:number
    };
    menu:{
    	...
    }[]
}

사용

let data:A

객체를 다시 타입으로

export type Address={
    	city:string;
    	phone:number
}

export type Menu={
    	...
}
=>
export type A = {
 	name:string;
    age:number;
    address:Address
    menu:Menu[]
}

useState

const[test, setTest]=useState<타입>(data)

props

const Store:React.FC = (props의 타입도 지정 보통 만들어서 사용) =>{
	return(
    ...
    )
}

interface 형태

interface OwnProps{
	info:A
}

적용

const Store:React.FC<OwnProps> = ({info}) =>{
	return(
    ...
    )
}

함수 props 타입지정

const changeA = (age:A) =>{
	...
}
interface OwnProps{
	info:A,
    changeA(age:A) :void <= 함수명(받는변수:타입) : 반환형
}

extends

커스텀 타입에 상속하는 개념

interface

interface A {
 	name:string;
    age:number;
    address:Address
    menu:Menu[]
}
interface child extends A {
 	childName:string;
    childAge:number;
}

이 안에는 자동으로 A타입의 변수들이 들어가있다

type

export type child = A & {
 	childName:string;
    childAge:number;
}

타입 형태 추가 기능

타입에서 제외

export type without = Omit<A, 'name'>

interface에도 적용가능

interface Own extends Omit<A, 'name'>{
...
}

타입에 pick

export type pick = Pick<A, 'name'>
<= A 타입에서 name만 가져온다

?

있을수도 있고 없을수도 있다

export type A = {
 	name:string;
    age:number;
    address:Address
    menu?:Menu[]
}

API 타입 생성예시

타입 선언

export type ApiRes<T> = {
  data:T[],
  pages:number
}
 

적용

export type MenuApiRes = ApiRes<Menu> 

결과

export type MenuApiRes = {
  data:Menu[],
  pages:number
}

0개의 댓글