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

115
Views
T extiende String como índice de tipo mapeado

En mi proyecto, estoy usando un tipo asignado (con string como claves):

 export type ConfigurableFieldsType<T extends string[]> = { [field in keyof T]: string }

En el siguiente método, estoy usando el tipo ( this.configurableFields es un objeto ConfigurableFieldsType ):

 private getConfigurableAttribute(attribute: C[number]): string { return this.configurableFields[attribute] }

Sin embargo, estoy recibiendo el error:

 Type 'C[number]' cannot be used to index type 'ConfigurableFieldsType<C>'.

Puede encontrar el ejemplo completo (con error reproducible) en este TS Playground o en el siguiente:

 export type ProductType<T extends string[]> = { // more variables configurableFields: ConfigurableFieldsType<T> } export type ConfigurableFieldsType<T extends string[]> = { [field in keyof T]: string } export class Product<C extends string[]> implements ProductType<C> { constructor( // more public parameters public configurableFields: ConfigurableFieldsType<C>, ) {} private getConfigurableAttribute(attribute: C[number]): string { return this.configurableFields[attribute] } }
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Tiene la intención de que ConfigurableFieldsType<["a", "b", c"]> evalúe algo como {a: string, b: string, c: string} , pero su definición actual daría como resultado [string, string, string] Esto se debe a que {[K in keyof T]: string} da como resultado un tipo de matriz asignada , T es un tipo similar a una matriz, y keyof T es, por lo tanto, las claves de la matriz, como "push" o "length" .

En su lugar, desea que las claves de su tipo sean elementos de T . Es decir, los tipos que obtienes cuando indexas en T con un índice numérico... así que en lugar de keyof T , quieres T[number] :

 export type ConfigurableFieldsType<T extends string[]> = { [K in T[number]]: string } type Example = ConfigurableFieldsType<["a", "b", "c"]> /* type Example = { a: string; b: string; c: string; } */

Y ahora las cosas funcionan como pretendes:

 private getConfigurableAttribute(attribute: C[number]): string { return this.configurableFields[attribute] // okay }

Enlace del patio de recreo al código

about 4 years ago · Santiago Gelvez 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!