TIL - Typescript의 Interface

Taesol Kwon·2020년 3월 28일
1

Typescript 하면서 중요하다고 느꼈던 Interface를 간단하게만 정리해보고자 한다.

Interface

Typescript의 핵심 기능 중 하나가 type-checking이다. Interface는 이러한 타입의 이름을 지정하는 역할을 한다. 지정한 type대로 값이 들어오지 않으면 에러가 발생한다.(최대한 any사용을 자제하자^^.) 보통 Component 내부에 지정해주거나 공통으로 계속 쓰이는 Interface의 경우에는 따로 파일을 만들어 import해서 필요할 때 쓴다.

export default interface User {
  id: number;
  name: string;
  eng_name?: string; //optional properties: 선택가능한 속성값(들어올수도 있고 안들어올수도 있는 값)
}

위의 공통 Interface를 폴더에 만들어 아래와 같이 불러와서 쓸 수 있다.

import React from 'react';
import User from "../interfaces/User.interface";

interface Props {
  content: string;
  data: Array<User>;
}

const App: React.FC<Props> = (props: Props) => {
  const { content, data } = props;
  return (
  	<div>
    	   <div>{content}<div>
           {data.map(item => {
               <div>{data.id}<div>
               <div>{data.name}<div>
               <div>{data.eng_name}<div>
           })}
    	<div/>
  )
}

이와 같이 적용할 수 있다. 자세한 내용은 Typescript Handbook을 참고하면 좋다. 다음번엔 Generic에 대해 적어보도록 하겠다.

profile
사진촬영을 좋아하는 프론트엔드 개발자입니다.

0개의 댓글