Extract- und Exclude-Typen in TypeScript

Level 5460 Tastenanschläge

Extract behält die Mitglieder einer Union, die einem zweiten Typ zuweisbar sind, Exclude entfernt sie. Mitglieder wie "whale", die nicht in Animal vorkommen, werden einfach ignoriert.

TypeScript-Code

// Union aus vier String-Literalen
1type Animal = "dog" | "cat" | "fish" | "bird";
// Behält Mitglieder, die auch in der zweiten Union stehen: "dog" | "cat"
2type Mammal = Extract<Animal, "dog" | "cat" | "whale">;
// "whale" ist nicht in Animal, daher bleibt nur "fish"
3type Aquatic = Extract<Animal, "fish" | "whale">;
// Entfernt "fish": "dog" | "cat" | "bird"
4type LandAnimal = Exclude<Animal, "fish">;
// Die Arrays dürfen nur Mitglieder der gefilterten Typen enthalten
5const mammals: Mammal[] = ["dog", "cat"];
6const aquatic: Aquatic[] = ["fish"];
7const land: LandAnimal[] = ["dog", "cat", "bird"];
// Verbindet mit ", "; gibt "Mammals: dog, cat" aus
8console.log(`Mammals: ${mammals.join(", ")}`);
// Gibt "Aquatic: fish" aus
9console.log(`Aquatic: ${aquatic.join(", ")}`);
// Gibt "Land: dog, cat, bird" aus
10console.log(`Land: ${land.join(", ")}`);

Ausgabe

Mammals: dog, cat
Aquatic: fish
Land: dog, cat, bird
Diesen Code tippen üben

Ü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.

  • "× 38
  • ;× 10
  • ,× 9
  • =× 7
  • :× 6
  • .× 6
  • (× 6
  • )× 6
  • [× 6
  • ]× 6

Weitere TypeScript-Beispiele auf Level 5

← TypeScript-Tippübungen