microsoft / microsoft/TypeScript
Easier use of indexed access types on nullable/optional types
Nadie ha tomado este issue todavía.
- 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
- 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, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
⭐ 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
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- 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