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

229
Views
¿Cómo usar tipos como valores en TypeScript? / Metatipos

Estoy trabajando en un componente que obtiene registros de una fuente de datos. El componente está escrito en TypeScript, con lo que no me siento muy cómodo.

Cada registro se caracteriza por una clave y el tipo de valor del registro. El método fetch toma una instancia de RecordDescriptor<Value> cuyo parámetro genérico Value determina el tipo de retorno del método.

En Swift, lograría el objetivo con el siguiente código, aprovechando los metatipos :

 struct RecordDescriptor<Value> { let key: String let valueType: Value.Type // `Value.Type` is a metatype, the type of a type } func fetchValue<Value>(for descriptor: RecordDescriptor<Value>) -> Value { // … } let intRecordDescriptor = RecordDescriptor(key: "int_record", valueType: Int.self) // `Int.self` refers to the `Int` type itself, not an instance of `Int` let intValue = fetchValue(for: intRecordDescriptor)

Básicamente puedo especializar el parámetro genérico Value sin usar instancias concretas de un tipo, solo el nombre del tipo en sí.

¿Cómo logro el mismo resultado en TypeScript?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No le importan los Metatypes por sus capacidades de sugerencia de tipo, solo le importan por su capacidad para

acceder a inicializadores u otros miembros estáticos de la clase o protocolo

Eso se escribe simplemente como:

 interface Newable { new(): any } type Constructable<T> = T extends Newable ? T : T extends (...args: any[]) => unknown ? T : never type RecordDescriptor<T, Key extends string> = { key: Key } & ( T extends Constructable<T> ? { transformation: T } // Replace this arm with `never` // to not allow scalars / non-classes like `boolean` : { transformation: (arg?: unknown) => T } )

El uso es:

 let descriptorN: RecordDescriptor<Number, "numbers"> = { key: "numbers", transformation: Number } let resultN: Number = descriptorN.transformation("123") let descriptorF: RecordDescriptor<(a: string, b: boolean) => string | boolean, "crazy"> = { key: "crazy", transformation: (a, b) => b ? "hi" : a.length > 3 } let resultF: string | boolean = descriptorF.transformation("hmm", true) let rp: RecordDescriptor<boolean, "options"> = { key: "options", transformation: () => true } let resultP: boolean = rp.transformation()

Enlace del patio de recreo

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!