microsoft / microsoft/TypeScript

Suggestion: type narrowing based on user-defined type guards against properties

Abierto
#35,846 2 comentarios 9 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
2 d 4 h
PR fusionados (30 d)
132

Descripción

Search Terms

user-defined type guards, type predicates, type narrowing, object properties

Suggestion

TS can narrow object types in if statements and other conditional control flows by various means. Particularly, if the object's type is a union type distinguishable by a "tag" (like Option<T> in the below example), we can narrow the type by checking the value of the tag. However, if the check for the tag is done by user-defined type guards against the property (but not the object itself), the object's type is not narrowed.

The suggestion is to make it work even if user-defined type guards are applied to object properties

Use Cases

The "tagged union" pattern is widely used in TS codebases. If tags theirselves are so complicated, we want to utilize user-defined type guards to check them.

Examples

type Option<T> = {
  type: "some"
  value: T
} | {
  type: "none"
}

const isSome = (type: "some" | "none"): type is "some" => type === "some"

declare const option: Option<number>

// Good: option is narrowed in the if block
if (option.type === "some") {
  option.value
}

// Bad: option isn't narrowed
if (isSome(option.type)) {
  // Error: Property 'value' does not exist on type 'Option<number>'.
  option.value
}

// Available workaround
const isSomeObject = <T>(option: Option<T>): option is Extract<Option<T>, { type: "some" }> => option.type === "some"

if (isSomeObject(option)) {
  option.value
}

playground

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

Comienza con el playground enlazado y los ejemplos de Option para reproducir la diferencia entre las comprobaciones directas de propiedades y los type guards definidos por el usuario. El issue no menciona ningún archivo de implementación ni ninguna prueba, así que localiza la lógica de control de flujo del estrechamiento de tipos y sus pruebas existentes antes de definir el cambio. Se considera completado cuando option.value se acepta después de isSome(option.type), mientras el comportamiento existente del estrechamiento se mantiene sin cambios.

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.