Cohe
React Router와 TypeScript를 활용한 프로젝트 가이드 본문
728x90
반응형
- 404 error 처리 → 권장은 element다.
- 403과 같은 처리는 x
- function App() { const {pathname} = useLocation(); return ( <Routes> <Route path='/*' element={ <div> <p>{pathname} 이 페이지는 존재하지 않습니다</p> </div> } />
- 타입 스크립트 만들기 mkdir ts-practics → cd ts-practics → npm inti
- 이럼 ts-practics 에 package.json이 생김, 거기에 아래와 같은 내용을 추가해주면 됨 (주석은 지우기)
, "compileroptions":{ "target": "es5", -> ES5방식으로 사용하겠다. ES6으로 설정하면 화살표 함수 사용이 가능 "module": "commonjs", -> 컴파일 된 코드가 어떤 모듈에서 실행할지 결정 "strict": true, -> 모든 타입체킹 옵션 활성화 "esModuleInterop": true, -> commonjs모듈 형태로 이뤄진 파일을 es2015 모듈 형태로 불러 올 수 있게 함 "outDir":"./dist" }
- npm install -g typescript or yarn global add typescript or npm install typescript 다운
- tsc --init 다운
- why typescript를 쓸까? 값 검증을 위해
- 예시
- const message: string = 'Hello, World!'; console.log(message)
- cmd에서 tsc를 침 → output이 생김, 우리는 .dist에 넣기로 해서 넣어짐 (난 왜 안돼??)
- 이후 node ./dist/practice.js 를 치면 우리가 설정해놓은게 실행된다.
- practice3.ts
// Generics
// 타입 스크립트에서 함수, 클래스, interface, type alias를 사용할 때
// 여러 종류의 타입에 대해서 호환을 맞춰야 하는 상황에서 사용하는 문법
// 함수에서 Generics 사용하기
// 객체와 객체를 합쳐주는 함수
function merge(a: any, b: any): any { // any는 어떤 타입이든 상관 없음 -> typescript쓰는 의미가 없어짐(값 검증)
return {
...a,
...b
}
}
const merged = merge({foo:1}, {bar:1});
console.log(merged);
// 이런 경우 Generics 사용하기
function merge2<A,B>(a: A, b: B): A & B {
return {
...a,
...b
}
}
const merged2 = merge2({foo:1}, {bar:1});
console.log(merged2);
function wrap<T>(param: T) {
return {
param
}
}
const wrapped = wrap(10);
console.log(wrapped)
const wrapped2 = wrap('hello');
console.log(wrapped2)
// const wrapped3 = wrap(<String>[1,2,3]); // error
// type에서 Generics 사용하기
type Person<T> = {
list2: T[];
}
const typeItems: Person<number> = {
list2: [1,2,3]
}
class Queue<T>{
list: T[] = [];
get length() {
return this.list.length;
}
enqueue(item: T) {
this.list.push(item);
}
dequeue() {
return this.list.shift();
}
}
const queue = new Queue<number>();
queue.enqueue(0);
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.length);
queue.dequeue();
console.log(queue.length);
queue.dequeue();
console.log(queue.length);
console.log(queue.dequeue());
- npm create react-app ts-react-tutorial --template typescript 만들기
- 일반적으로 TypeScript로 생성된 React 파일의 확장자는 .tsx 이다.
- 만일 기존의 리액터에 TypeScript를 추가 하고 싶다면? https://create-react-app.dev/docs/adding-typescript/ 추가하면 됩니다
- npm install --save typescript @types/node @types/react @types/react-dom @types/jest
- ⇒ 깃허브에 반영~ https://github.com/CheHyeonYeong/JavascriptStudy/commit/9fa11f7bcda4b8bf954e196ffacc03aeebc20c64 요기 즈음임
728x90
반응형
'JavaScript, React' 카테고리의 다른 글
반응형 웹 디자인 (0) | 2024.09.02 |
---|---|
React Router를 활용한 SPA 구현 가이드 (0) | 2024.06.25 |
React - API 연동 (0) | 2024.06.25 |
React - ContextAPI 사용방법 (0) | 2024.06.25 |
Next.js 프로젝트 수동 및 자동 생성 방법 및 라우팅 기초 (0) | 2024.06.25 |