microsoft / microsoft/TypeScript

Add named type arguments

Abierto
#38,913 8 comentarios 33 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

generics, type parameters, named parameter, named type parameter, type argument, named type argument

Suggestion

It should be possible to pass type arguments to a generic by name rather than positionally, eg.

interface Foo<T = SomeDefaultType, U> { ... }

// Current syntax
const foo: Foo<SomeDefaultType, string> ...

// Proposed syntax
const foo: Foo<U = string> ...
// yields foo: Foo<SomeDefaultValue, string>

This is loosely inspired on python's named arguments:

def foo(bar = "I'm bar", baz):
    ...

foo(baz="I'm baz")

Use Cases

Generics only accept positional type arguments. If you have a generic accepting many type arguments, most or all of which having default values such as:

interface Handler<Type = string, TPayload = object, TOutput = void> {
  type: Type
  handle(payload: TPayload): TOutput
}

Let's say we have a class which implements the Handler interface but the defaults for Type and TPayload are fine for us and we only want to specify a type for TOuput, currently it is mandatory that we pass type arguments for Type and TPayload:

class Foo implements Handler<string, object, Promise<number>>

If it was possible to pass type arguments by name we could use the considerably terser form:

class Foo implements Handler<TOutput=Promise<number>>

Examples

Fastify exposes types generic over many parameters with default values, such as

  interface FastifyRequest<
    HttpRequest = http.IncomingMessage,
    Query = DefaultQuery,
    Params = DefaultParams,
    Headers = DefaultHeaders,
    Body = DefaultBody
  > { ...

With the proposed syntax we could create specialized interfaces with much less overhead such as

import * as fastify from 'fastify';

const app = fastify();
app.get('/users/:id', async (req: FastifyRequest<Params = {id: string }>, res: FastifyReply) => {
   // req.params is strongly typed now
})

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

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

El issue describe argumentos de tipo con nombre para los genéricos de TypeScript e incluye ejemplos de sintaxis con valores predeterminados y tipos de Fastify. No se especifican archivos de implementación, pruebas ni puntos de entrada; comienza localizando las áreas del compilador que analizan y comprueban los argumentos de tipo genéricos. Se considera completado cuando los argumentos con nombre pueden seleccionar parámetros de tipo posteriores conservando los valores predeterminados anteriores, con cobertura para los ejemplos del issue.

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
30/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.