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?
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()