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

80
Views
Crear una firma de índice en Typescript con las claves requeridas Y opcionales

Estoy tratando de encontrar una solución más elegante para crear un tipo que permita que ciertas claves de su firma de índice sean opcionales.

Este puede ser un caso de uso para genéricos, pero parece que no puedo descifrarlo.

Actualmente construyéndolo así:

 // Required and optional keys allowed as indexes on final type type RequiredKeys = 'name' | 'age' | 'city' type OptionalKeys = 'food' | 'drink' // Index types use to combine for final type type WithRequiredSignature = { [key in RequiredKeys]: string } type WithOptionalSignature = { [key in OptionalKeys]?: string } // Build type with required and optional properties on index signature type FinalType = WithRequiredSignature & WithOptionalSignature // Test objects with functional autocomplete const test1: FinalType = { name: 'Test', age: '34', city: 'New York' } const test2: FinalType = { name: 'Test', age: '34', city: 'New York', drink: 'Beer' } const test3: FinalType = { name: 'Test', age: '34', city: 'New York', food: 'Pizza' }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Su solución está bien si obtiene las claves dinámicamente. Si no es así, ¿por qué no simplemente hacer una interfaz?

 interface FinalType { name: string; age: number; city: string; food?: string; drink?: string; }
about 4 years ago · Juan Pablo Isaza 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!