Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

413
Views
TypeScript: especifique que el valor debe estar en Array usando el operador de extensión

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"}; // ERROR
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Encontré 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"
over 4 years ago · Santiago Trujillo Report

0

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

Puedes probar aquí

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!