Fabrik für diskriminierte Unions in TypeScript
Level 5600 Tastenanschläge
Ein generischer Action-Typ erzeugt { type } oder { type, payload }, je nachdem, ob ein Payload-Typ angegeben ist. Der Reducer verzweigt über type, und TypeScript weiß in jedem case, welcher payload vorhanden ist.
TypeScript-Code
// P ist standardmäßig void und bedeutet "kein Payload"1type Action<T extends string, P = void> = P extends void // Ohne Payload: nur das Feld type2 ? { type: T } // Mit Payload: type plus ein payload vom Typ P3 : { type: T; payload: P };// Ergibt { type: "LOADING" }4type LoadingAction = Action<"LOADING">;// Aktionen mit Payload für Erfolg und Fehler5type SuccessAction = Action<"SUCCESS", { data: string[] }>;6type ErrorAction = Action<"ERROR", { message: string }>;// Union, die über das Feld type unterschieden wird7type AppAction = LoadingAction | SuccessAction | ErrorAction;8function reducer(action: AppAction): string { // Die Prüfung von type verengt action in jedem case9 switch (action.type) {10 case "LOADING": return "Loading..."; // Hier ist action ein SuccessAction, daher ist payload.data verfügbar11 case "SUCCESS": return action.payload.data.join(", "); // Hier ist action ein ErrorAction mit payload.message12 case "ERROR": return action.payload.message;13 }14}// Verbindet ["a", "b"] und gibt "a, b" aus15console.log(reducer({ type: "SUCCESS", payload: { data: ["a", "b"] } }));Ausgabe
a, b
Übe, diesen Code zu tippen. Ergebnisse werden nicht in der Rangliste gespeichert.
Symbole in diesem Code
Die Symbole, die du in diesem TypeScript-Code tippst, und wie oft sie vorkommen.
"× 22:× 14;× 10.× 10{× 8}× 8,× 6=× 6(× 5)× 5