React TypeScript Project सेट अप करना
In this page:
एक React TypeScript Project बनाना
एक React + TypeScript project बनाना (Vite या Create React App के TypeScript template के through) एक project scaffold करता है जहां component files .tsx extension उपयोग करती हैं, जो JSX syntax को TypeScript के type annotations के साथ-साथ allow करता है।
उदाहरण: Creating a React TypeScript Project
// npm create vite@latest my-app -- --template react-ts
console.log("Scaffolds a project where components use the .tsx extension");
एक TSX Component लिखना
एक TSX component लिखने का मतलब है file JSX markup को typed props और typed local variables के साथ एक ही function में mix कर सकती है, .tsx extension compiler को यह बताते हुए कि < को comparison operator treat करने के बजाय JSX tags parse करना है।
उदाहरण: Writing a TSX Component
import React from "react";
function Greeting(): React.JSX.Element {
const name: string = "Ravi";
return <h1>Hello, {name}</h1>;
}
export default Greeting;
Component Variables को Type करना
Component variables को type करना — जैसे state, refs, या component के अंदर computed values — normal TypeScript rules follow करता है, क्योंकि एक React component आखिरकार सिर्फ एक typed function है जो JSX return करता है।
उदाहरण: Typing Component Variables
import React from "react";
function Counter(): React.JSX.Element {
const initialCount: number = 0;
return <p>Count: {initialCount}</p>;
}
export default Counter;
TypeScript Configuration उपयोग करना
एक React project में TypeScript configuration उपयोग करना typically tsconfig.json में jsx को react-jsx set करता है, compiler को यह बताते हुए कि JSX syntax को React के runtime पर expect किए actual function calls में कैसे transform करना है।
उदाहरण: Using TypeScript Configuration
// tsconfig.json
// { "compilerOptions": { "jsx": "react-jsx" } }
console.log("jsx: react-jsx tells the compiler how to transform JSX");
एक Typed App के साथ शुरुआत करना
एक पूरी तरह typed app template से शुरू करने का मतलब है कि props, state, और event handlers आपके लिखे पहले ही component से check होते हैं, एक misspelled prop name जैसी mismatches को app कभी browser में चलने से पहले ही पकड़ते हुए।
उदाहरण: Starting with a Typed App
import React from "react";
interface AppProps {
title: string;
}
function App({ title }: AppProps): React.JSX.Element {
return <h1>{title}</h1>;
}
export default App;
- एक component file का नाम
.tsxके बजाय.tsरखना, इसलिए JSX markup एक syntax error बन जाता है। tsconfig.jsonमें"jsx"set करना भूल जाना (जैसेreact-jsx), इसलिए JSX compile नहीं होता।.tsxfiles के अंदर<T>valuecasts लिखना, जब angle-bracket assertions JSX से clash करते हैं (इसके बजायasउपयोग करें)।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: