TypeScript in React

1. Typisierung von Props

ThemaSyntax / BeispielBeschreibung
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 = {
  children: React.ReactNode;
  style?: React.CSSProperties;
};
 
const Container = ({ children, style }: ContainerProps) => (
  <div
    style={{
      border: '2px dashed #888',
      padding: '1rem',
      borderRadius: '0.5rem',
      backgroundColor: '#f9f9f9',
      fontFamily: 'sans-serif',
      ...style
    }}
  >
    {children}
  </div>
);

const App = () => {
  return (
    <Container style={{ maxWidth: '600px', margin: '0 auto' }}>
      <h1>My React App</h1>
...
    </Container>
  );
};

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

    SzenarioSyntax / BeispielBeschreibung / Hinweise
    Inferred Statets const [count, setCount] = useState(0); Typ wird vom Initialwert abgeleitet.
    Kein explizites Generic nötig.
    State mit null/undefined„`ts const [user, setUser] = useState<stringnull>(null); // Startwert null, Typ string oder null„`
    Array Statets 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<stringnull>(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 Guardingts if (!posts) return <p>No posts found.</p>;Verhindert Runtime-Fehler, wenn der State möglicherweise undefined oder leer ist.
    Generics in useStatets const [items, setItems] = useState<ItemType[]>([]);Generics ermöglichen präzise Typisierung unabhängig vom Startwert.
    Boolean / Loading Statets const [loading, setLoading] = useState<boolean>(true);Boolesche States können oft automatisch erkannt werden, explizite Typisierung optional.