[프로젝트 타입 관리] React Native(Expo CLI)와 함께 TypeScript 사용

fejigu·2023년 3월 29일
2

React Native Project

목록 보기
5/17
post-thumbnail


🔎 TypeScript

✔️ TypeScript란

→ TypeScript는 JavaScript의 상위 집합인 오픈소스 프로그래밍 언어로, JavaScript 언어에 포함되지 않은 선택적 정적 타이핑, 클래스, 인터페이스 및 기타 기능을 추가합니다.

✔️ TypeScript를 사용하는 이유

→ TypeScript의 주요 목표는 런타임이 아닌 컴파일 타임에 오류를 포착하여 대규모의 복잡한 애플리케이션을 더 쉽게 작성할 수 있도록 하는 것입니다.

정적 유형을 추가함으로써 TypeScript는 함수에 잘못된 유형의 인수를 전달하거나 객체에 존재하지 않는 프로퍼티에 액세스하는 등 유형 관련 오류를 감지하는 데 도움을 줄 수 있습니다.

✔️ 기본적인 문법 리마인드

//tsconfig.json
//터미널 켜서 tsc -w 입력 해두면 자동 변환을 도와줌.
{
  "extends": "expo/tsconfig.base",
  "compilerOptions": {}
}
//index.ts
// Import stylesheets
import './style.css';

//type 지정 : string, number, boolean, null, undefined, bight,[],{}

//let name :string = "an";
//let name : string[] = ["an", "lee"]
//name 속성은 옵션이다, 들어오지 않다고 에러 처리 X
let name :{ name? : string} = { name : "an" }

//타입으로 숫자와 문자 둘다 들어와야 허는 경우라면? union type
let union :string | number = 123;

//타입은 변수(대문자로 작명)에 담아서 쓸 수 있음! Type alias
type Mytype = string | number;
let newname :Mytype = 1234;

//함수에도 타입지정 가능
//아래 함수는 파라미터로 number, return 값으로 number
function Fnc(x:number) :number{
  return x * 2
}

//array에 쓸 수 있는 tuple 타입
//아래의 경우 무조건 첫번째는 number, 두번째는 boolean이 들어와여한다
type Member = [number, boolean];
let zone:Member = [123, true];

//object에 타입 지정해야할 속성이 너무 많다면
//글자로 된 모든 object 속성의 타입은 string
type MemberList = {
  [key : string]  : string,
}
let people : MemberList = { name : "an", age : '20'}


//class 타입 지정 가능
//미리 변수의 타입 지정을 해야한다
class User {
  name : string;
  constructor(name :string){
    this.name = name;
  }
}

// Write TypeScript code!
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = `<h1>TypeScript Starter</h1>`;



🔎 React Native(Expo CLI) with Typescript

1. 프로젝트 시작

//타입스크립트 템플릿
npx react-native init MyApp --template react-native-template-typescript
//expo 타입스크립트 템플릿
npm install -g expo-cli
expo init MyTSProject

2. TypeScript와 React Native의 작동 방식

→ 기본적으로 파일을 JavaScript로 변환하는 작업은 TypeScript를 사용하지 않는 React Native 프로젝트와 동일한 Babel 인프라를 통해 이루어집니다. TypeScript 컴파일러는 타입 검사에만 사용하는 것이 좋습니다.

3. React Native + TypeScript

//tsconfig.json
{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react-native",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}
//App.tsx
import React from 'react';
import { View, Text } from 'react-native';

interface AppProps {
  name: string;
}

const App: React.FC<AppProps> = ({ name }) => {
  return (
    <View>
      <Text>Hello, {name}!</Text>
    </View>
  );
};

export default App;


참고자료

profile
console.log(frontendjigu( ☕️, 📱); // true

0개의 댓글