1. Typisierung von Props
| Thema | Syntax / Beispiel | Beschreibung |
|---|---|---|
| Props typisieren | type GreetingProps = { name: string };const Greeting = ({ name }: GreetingProps) => ... | Props werden über Type Aliases typisiert, IntelliSense und Typprüfung inklusive |
| Optionale Props & Defaults | type ButtonProps = { label: string; colour?: string };const Button = ({ label, colour = 'blue' }: ButtonProps) => ... | ?Props sind optionale Angabe Default-Werte werden mit = zugewiesen |
| Union Types für Prop Varianten | type StatusProps = { status: 'loading' | 'success' | 'error';};const Status = ({ status }: StatusProps) => { return <p>Status: {status}</p>;};const App = () => { return ( <div> <h1>My React App</h1> <Status status='success' /> <Status status='loading' /> <Status status='error' /> <Status status='thinking' /> // ❌ not assignable </div> );}; | Union Types schränken den Umfang der validen Werte ein |
| Children Props | type ContainerProps = { | Für Wrapper- oder Layout-Komponenten:React.ReactNode typisiert beliebige HTML-Kind-Elemente React.CSSProperties typisiert Styling-Werte |
| Inline vs. separate Types | type XProps = {...} interface XProps {...}#TODO | Inline- oder InFile-Typen für lokale Nutzung separate Type-Files nur bei mehrfacher Verwendung |
2. Typisierung von States
| Szenario | Syntax / Beispiel | Beschreibung / Hinweise |
|---|---|---|
| Inferred State | ts const [count, setCount] = useState(0); | Typ wird vom Initialwert abgeleitet. Kein explizites Generic nötig. |
| State mit null/undefined | „`ts const [user, setUser] = useState<string | null>(null); // Startwert null, Typ string oder null„` |
| Array State | ts type Post = { id: number; title: string; body: string }; const [posts, setPosts] = useState<Post[]>([]); | Generic <Post[]> definiert das Array und die Form der Elemente. Anfangs leer. |
| String oder Null für Error | „`ts const [error, setError] = useState<string | null>(null); // Fehlernachricht oder kein Fehler„` |
| Object State (Inline Inference) | ts const [user, setUser] = useState({ name: 'Ada', age: 36 }); // TypeScript erkennt { name: string; age: number } | Initialer State definiert Typ. Später neue Properties, die nicht existieren, erzeugen Fehler. |
| Object State (Explicit Type) | ts type UserType = { name: string; age: number; email?: string }; const [user, setUser] = useState<UserType>({ name: 'Ada', age: 36 }); | Bessere Lesbarkeit und sichere Erweiterbarkeit, besonders bei komplexen oder geteilten Objekten. |
| State Guarding | ts if (!posts) return <p>No posts found.</p>; | Verhindert Runtime-Fehler, wenn der State möglicherweise undefined oder leer ist. |
| Generics in useState | ts const [items, setItems] = useState<ItemType[]>([]); | Generics ermöglichen präzise Typisierung unabhängig vom Startwert. |
| Boolean / Loading State | ts const [loading, setLoading] = useState<boolean>(true); | Boolesche States können oft automatisch erkannt werden, explizite Typisierung optional. |