728x90
반응형
SMALL
타입스크립트가 적용된 리액트 네이티브 프로젝트 만들기
프로젝트 생성 시,
--template react-native-template-typescript
코드를 붙여서 생성함
기본 타입
파일 생성 시, 확장자를 ts 또는 tsx로 설정함.
- 리액트 컴포넌트 작성 시 tsx로 설정해야 함.
타입 지정 시 변수 이름 뒤에
: 타입
형태로 지정하여 작성
기본 타입은 자동 추론하여 생성함.
let message = 'Hello World';
위와 같이 변수 선언 가능
함수 타입
함수도 자동 추론 가능
예시)
function sum(a: number, b:number) {
return a + b;
}
const result = sum(1, 2);
위와 같이 리턴값 타입 지정 하지 않아도 오류나지 않음.
function sum(a: number, b:number) : number {
return a+b;
}
위와 같이 리턴값 정의하는게 원칙
옵셔널 파라미터
생략해도 되는 파라미터, 뒤에 '?' 붙여서 생성
예시)
function process(a: number, b: number, isDouble?: boolean) {
const sum = a+b;
return isDouble ? sum * 2 : sum;
}
const total = process(1, 2);
const doubleTotal = process(1, 2, true);
여기서 is Double의 타입은 boolean | undefined임.
interface
객체나 클래스를 위한 타입을 정할 때 사용
예시)
interface Profile {
id: number;
username: string;
displayName: string;
}
function printUsername(profile: Profile) {
console.log(profile.username);
}
const profile: Profile = {
id: 1,
username: 'velopert',
displayName: 'Minjun Kim',
};
printUsername(profile);
아래와 같이 재참조도 가능함
interfacd Relationship {
from: Profile;
to: Profile;
}
const relationship: Relationship = {
from: {
id: 1,
username: 'velopert',
displayName: 'Minjun Kim',
},
to: {
id: 2,
username: 'john',
displayName: 'Sungmin Kim',
},
};
아래와 같이 상속도 가능함
interface Account extends Profile {
email: string;
password: string;
}
const account: Account = {
id: 1,
username: 'johndoe',
displayName: 'John Doe',
email: 'john@email.com',
password: '123123',
};
(클래스에서도 implements 상속 가능함)
배열 타입
[] 붙여서 생성함
예시)
const numbers: number[] = [1,2,3,4,5];
const texts: string[] = ['hello', 'world'];
interface Person {
name: string;
}
const people: Person[] = [{name: 'John'}, {name: 'Doe'}];

728x90
반응형
LIST
'Typescript' 카테고리의 다른 글
| Typescript) React Native에 Typescript 적용하기 - 3 (0) | 2023.09.10 |
|---|---|
| Typescript) React Native에 Typescript 적용하기 - 2 (0) | 2023.09.09 |