microsoft / microsoft/TypeScript

Feature Request: Instantiate Generic Functions within Conditional Types

Abierto
#61,133 4 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Awaiting More Feedback Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.3k
Merge medio
2 d 4 h
PR fusionados (30 d)
132

Descripción

🔍 Search Terms

Instantiation Expressions, Conditional Types

✅ Viability Checklist
⭐ Suggestion

I am looking for a way to be able to instantiate a generic function / return type via conditional type.

// some method

declare function method<T>(value: T): T

// ... this is possible

type R0 = ReturnType<typeof method<number>> 

// ... but this isn't 

type Infer<Func extends <T>(value: T) => unknown, U> = ReturnType<Func<U>>

type R1 = Infer<typeof method, number>

Related Issue: https://github.com/microsoft/TypeScript/issues/22617

📃 Motivating Example

I have written a small type-level parser for one of the libraries I manage. I have support for type parameterization.

Parameterized Type

const T = Syntax('number') 

const Vector = Syntax({ T }, `{ x: T, y: T, z: T }`)  // const T: TObject<{
                                                      //   x: TNumber,
                                                      //   y: TNumber,
                                                      //   z: TNumber
                                                      // }>

... but would also like to support generic functions as parameters (and resolve exterior types via function call / instantiation expression)

const Vector = <T extends TSchema>(T: T) => Type.Object({ x: T, y: T, z: T })

const T = Syntax({ Vector }, `Vector<number>`)        // const T: TObject<{
                                                      //    x: TNumber,
                                                      //    y: TNumber,
                                                      //    z: TNumber
                                                      // }>
                                      

When implementing the second case, I noticed it's not actually possible to instantiate the Vector signature within the context of a conditional type expression (i.e. the parser). In this case, I have a parsed TNumber type ready to supply the generic Vector function, but no way to instantiate it.

Essentially I would need the following but in a conditional type (Reference)

const Vector = <T extends TSchema>(T: T) => Type.Object({ x: T, y: T, z: T })

// ... internal to the parser

type ParsedNumber = TNumber 

type Instanced = ReturnType<typeof Vector<ParsedNumber>> // need this via conditional type
💻 Use Cases
  1. What do you want to use this for?

Implement generic types in a type level syntax parser.

  1. What shortcomings exist with current approaches?

Cannot instantiate generic signatures within a conditional type.

  1. What workarounds are you using in the meantime?

I'm not sure there are workarounds.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con el comportamiento de los tipos condicionales y las expresiones de instanciación descrito en los ejemplos y, después, revisa el issue relacionado #22617. Se considera terminado cuando las firmas de funciones genéricas puedan instanciarse con argumentos de tipo proporcionados desde un tipo condicional, incluidos los casos mostrados de Infer y Vector, sin cambiar el JavaScript emitido.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
typescript
Área
compilers
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.