Estoy tratando de definir un tipo donde el valor de la propiedad favoriteFruit debe ser un elemento en la matriz de opciones. Donde la matriz de opciones es dinámica/desconocida (lo que hace imposible usar tipos de unión "|").
const options = ["apple", "orange", "kiwi"]; // Dynamic list that can be modified in the future type Person = { name: string; favoriteFruit: /* --- val in [...options] --- */ }; const personA:Person = {name: "Jack", favoriteFruit: "apple"}; // OK const personB:Person = {name: "John", favoriteFruit: "orange"}; // OK const personC:Person = {name: "Jane", favoriteFruit: "banana"}; // ERROREncontré esto: ¿Cómo convertir una matriz de cadenas a tipos de escritura mecanografiada? .
const arr = ["foo", "bar", "loo"] as const type arrTyp = typeof arr[number]; // "foo" | "bar" | "loo"Espero que esto sea lo que estás buscando.
[ACTUALIZADO]
const options = ["apple", "orange", "kiwi"] as const; // Dynamic list that can be modified in the future type optionsType = typeof options[number]; type Person = { name: string; favoriteFruit: optionsType;/* --- val in [...options] --- */ }; const personA:Person = {name: "Jack", favoriteFruit: "apple"}; // OK const personB:Person = {name: "John", favoriteFruit: "orange"}; // OK const personC:Person = {name: "Jane", favoriteFruit: "banana"}; // ERROR console.log(personC)puede mantener su lista de opciones dinámica