Explica este código TypeScript
Dificultad: Avanzado
type Animal = "perro" | "gato" | "conejo";
type ConteoAnimal = {
[U in Animal]: number;
}
const miAnimal:ConteoAnimal = {
perro:20,
gato:30,
}
- A.
TypeError
- B.
Property 'conejo' is missing in type '{ perro: number; gato: number; }' but required in type 'ConteoAnimal'
- C.
Todo funciona bien
- D.
Ninguna de las anteriores
✅ B. En TypeScript tenemos los Mapped Types. Sirven para relacionar dos types entre si para un fin en común.
Respuesta
Property 'conejo' is missing in type '{ perro: number; gato: number; }' but required in type 'ConteoAnimal'
En este caso relacionamos el tipo literal Animal
con ConteoAnimal
. El generico U
de [U in Animal]
establece que el tipo ConteoAnimal
debe tener como llaves todos los literales de Animal
, por ello al crear el objeto miAnimal
y no tener la llave conejo falla.
Top comments (0)