microsoft / microsoft/TypeScript

Optional chaining should always include `undefined` in its resolved type

Abierto
#36,672 2 comentarios 5 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

In Discussion Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.3k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

TypeScript Version: 3.7.5

Search Terms: optional chaining return type

Code

I have a formatting function, where the input should always be a string, but in certain cases, from the backend, it's undefined for some reason. So to make sure the front-end at least doesn't crash when that happens, I added optional chaining, which fixed the issue.

But the types are kind of off now, and I didn't realize until now because Typescript didn't complain about anything.

export const formatAccountNumber = (account: string): string =>
  account?.replace(/^(\d{4})(\d{2})(\d{5})/, '$1 $2 $3');

Expected behavior: Should get an error/warning about something here. Preferably, I guess optional chaining should always expand the type to include undefined to whatever it is added to? Then, in this example, Typescript could say that the return type is string, but I'm trying to return string | undefined? Either that, or maybe it shouldn't be possible to use optional chaining on a value that does not include either the type undefined and/or null?

Actual behavior: No warnings or errors.

Related Issues: no

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 reproduciendo el ejemplo de TypeScript 3.7.5 con optional chaining y su tipo de retorno string explícito. Determina si la corrección prevista consiste en incluir undefined en el tipo resuelto o en rechazar optional chaining sobre valores no anulables; se considerará terminado cuando el comportamiento elegido se aplique de forma coherente y esté cubierto por pruebas del compilador.

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

Evaluación

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.