microsoft / microsoft/TypeScript

Easier use of indexed access types on nullable/optional types

Abierto
#59,293 3 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.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

🔍 Search Terms

index access types optional nullable

✅ Viability Checklist
⭐ Suggestion

I would like a more succint way to access types from a nested object that contains nullable fields.

Possibly by allowing ! in a type-level position as a shorthand for NonNullable<T>

📃 Motivating Example

Generated types representing API responses often contain useful types that you'd prefer to extract rather than repeating them elsewhere. This comes up quite often for me when using graphql codegen on a query with a deeply nested response payload.

eg.

type APIResponse = {
	items: {
		id: string;
		author?: {
            id: string;
			name: string;
            status: "owner" | "admin" | "contributor" | "freeloader";
		}
	}[];
	pagination: {
		next_page: string;
	}
}

This example is a bit contrived, but is fairly representative of the general problem.

If I try and extract the status property, this doesn't work:

type APIAuthor = APIResponse['items'][0]['author']['status'];
//     Property 'status' does not exist on type '{ id: string; name: string; status: "owner" | "admin" | "contributor" | "freeloader"; } | undefined'.

Unless I wrap with NotNullable, and then it does.

type APIAuthor = NonNullable<APIResponse['items'][0]['author']>['status'];

Conceptually, I think the ! operator could work nicely here, giving us

type APIAuthor =APIResponse['items'][0]['author']!['status'];
💻 Use Cases

I've covered this a bit under the "motivating example" section, so maybe I've misused the headers a bit.

This comes up quite often for me when using graphql codegen on a query with a deeply nested response payload.

My current workaround is use of NonNullable, but when there's multiple layers of optionality it gets very difficult to follow.

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 ejemplo motivador de APIResponse y compara la sintaxis ! propuesta a nivel de tipos con el workaround existente de NonNullable. Determina el comportamiento previsto para los accesos indexados opcionales y nullable anidados, y luego define casos de aceptación que demuestren que la forma abreviada produce el mismo tipo extraído sin cambiar la salida de JavaScript.

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.