[RN] React Native에 TypeScript 적용하기

Subin·2023년 8월 31일
2

리액트네이티브

목록 보기
2/13
post-thumbnail

💡 본 게시글은 React Native 공식문서의 내용을 참고했습니다.

완성된 코드는 깃허브에서 확인 가능합니다.

TypeScript에 필요한 패키지 설치

TypeScript, types, ESLint plugins를 설치합니다.

npm

npm install -D @tsconfig/react-native @types/jest @types/react @types/react-test-renderer typescript

Yarn

yarn add --dev @tsconfig/react-native @types/jest @types/react @types/react-test-renderer typescript

tsconfig.json 추가

React Native 프로젝트 루트에 tsconfig.json 파일을 생성합니다.

그 후에 아래의 코드를 입력하면 됩니다.
@tsconfig/react-native를 설치했기에 간단한 코드로 설정됩니다.

{
	"extends": "@tsconfig/react-native/tsconfig.json"
}

App.tsx

기존의 App.js를 App.jsx로 바꾸면 TypeScript로 개발할 수 있게 됩니다.

import React from "react";
import { Button, StyleSheet, Text, View } from "react-native";

export type Props = {
  name: string;
  baseEnthusiasmLevel?: number;
};

const App: React.FC<Props> = ({ name, baseEnthusiasmLevel = 0 }) => {
  const [enthusiasmLevel, setEnthusiasmLevel] =
    React.useState(baseEnthusiasmLevel);

  const onIncrement = () => setEnthusiasmLevel(enthusiasmLevel + 1);
  const onDecrement = () =>
    setEnthusiasmLevel(enthusiasmLevel > 0 ? enthusiasmLevel - 1 : 0);

  const getExclamationMarks = (numChars: number) =>
    numChars > 0 ? Array(numChars + 1).join("!") : "";

  return (
    <View style={styles.container}>
      <Text style={styles.greeting}>
        Hello {name}
        {getExclamationMarks(enthusiasmLevel)}
      </Text>
      <View>
        <Button
          title="Increase enthusiasm"
          accessibilityLabel="increment"
          onPress={onIncrement}
          color="blue"
        />
        <Button
          title="Decrease enthusiasm"
          accessibilityLabel="decrement"
          onPress={onDecrement}
          color="red"
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  greeting: {
    fontSize: 20,
    fontWeight: "bold",
    margin: 16,
  },
});

export default App;

React Native 설치

React Native 프로젝트를 처음 설치할 때 Typescript를 동봉할 수 있습니다.

react-native init project-name --template typescript

또는 CRNA로 프로젝트를 생성할 때 템플릿을 고를 수 있습니다.

npx create-react-native-app

profile
고양이가 세상을 지배한다.

1개의 댓글

comment-user-thumbnail
2023년 9월 1일

대단하시군요!

답글 달기