타입스크립트 기초

강준호·2024년 2월 19일

리액트

목록 보기
16/18

TypeScript

npm install -g typescript
npm install -D typescript


npx create-react-app my-app --template typescript
  • -D 붙이면 프로젝트 단위로 설치

함수는 매개변수, 결과값 타입을 결정해줘야해.


interface

  • 인터페이스는 객체의 형태를 정의해요
    interface User {
    id: number;
    name: string;
    }

type 키워드란?

- 타입스크립트에서 `type` 키워드를 사용하여 새로운 타입을 정의할 수 있어요.
- 인터페이스와 유사하지만, 더 유연한 타입 정의가 가능하고, 유니언 또는 인터섹션 타입을 쉽게 조합할 수 있어요.

typeinterface의 차이

- `interface`는 주로 객체의 모양을 정의할 때 유용해요.
- `type`은 `interface`에 없는 유니언 또는 인터섹션 타입과 같은 고급 타입을 표현하는 데 더 적합해요.
- `type`은 `interface`와 달리 확장(extends)이 불가능하지만, 타입 별칭을 생성할 때 더 유연해요.
type Point = {
  x: number;
  y: number;
};

type ID = number | string;

const point: Point = { x: 10, y: 20 };
const userId: ID = "user123";
ComponentProps <typeof Post>

제네릭

  • 타입을 재사용 가능하게

제네릭 유틸리티 타입

Required

  • 필수로 넣어야하는

Omit

  • 생략 가능한
export type StudentWithGender = Required<Student>
  

export type StudentWithOnlyName = Omit<Student,"gender">

children 은

PropsWithChildren<DisplayProps>

엘리먼트는 함수가 아님.

  const [movies, setMovies] = useState<>({ nowPlaying: [], topRated: [] });

movies 의 타입으로 주고싶은걸 useState의 제네릭 설정

인터페이스는 프롭스 설정할때만 쓰고, 나머지는 타입 키워드로 잡아줘

0개의 댓글