728x90
반응형
SMALL
타입스크립트가 적용된 리액트 네이티브 프로젝트 만들기
프로젝트 생성 시,
--template react-native-template-typescript
코드를 붙여서 생성함
Type Alias
타입에 별칭 붙임. interface 처럼 객체의 타입 지정 가능
type Person = {
name: string;
};
const person: Person = {
name: 'John';
};
type People = Person[];
const people: People = [{name: 'John'}];
type Color = 'red' | 'orange' | 'yellow';
const color: Color = 'red';
객체 타입은 interface 나 type 중 취향에 따라 사용하면 됨.
객체 필드 추가 시, '&' 기호 사용
type Employee = Person & {
job: string;
};
const employee: Employee = {
name: 'John',
job: 'Programmer',
};
Generic
함수, 객체, 클래스에서 사전에 정하지 않은 타입을 다룰 때 사용.
예시)
function wrap<T>(value: T) {
return {value};
}
interface Person {
name: string;
}
const person: Person = {name: 'John'};
const result = wrap(person);
console.log(result.value.name);
정의되지 않은 객체의 값을 동적으로 사용할 수 있음.
Props 사용하기
타입스크립트에서 Props 사용하기 위해서는 interface로 Props 를 미리 선언해서 사용함
예시 - Profile.tsx)
import React from 'react';
import { View, Text } from "react-native";
interface Props {
name: string;
}
function Profile({name}: Props) {
return (
<View>
<Text>{name}</Text>
</View>
);
}
export default Profile;
예시 - App.tsx
import React from 'react';
import Profile from './Profile';
function App() {
return <Profile name="John" />;
}
export default App;
옵셔널 Props는 Props 인터페이스의 파라미터에 ?를 붙여서 만듬
Props 기본값 설정은 구조분해 문법을 사용해서 컴포넌트 정의 단계에서 기본값을 파라메터 형태로 선언함.
function Profile({name = 'John'}: Props) {
(...)
children Props 사용하기
JSX 타입의 Props를 받아와야되는 상황에서는 React.ReacNode 타입으로 파라메터 선언해야 함
예시)
interface Props {
name: string,
children?: React.ReactNode;
}
function Profile({ name, children }: Props) {
return (
<View>
<Text>{name}</Text>
<View>{children}</View>
</View>
);
}
(...)
728x90
반응형
LIST
'Typescript' 카테고리의 다른 글
Typescript) React Native에 Typescript 적용하기 - 3 (0) | 2023.09.10 |
---|---|
Typescript) React Native에 Typescript 적용하기 - 1 (0) | 2023.09.09 |