microsoft / microsoft/TypeScript

Permit functions that return a value to also serve as a type guard

Abierto
#31,376 2 comentarios 8 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

Linear type, affine type, type guard

Suggestion

It would be very helpful to allow a function to serve as a type guard, but also return an unrelated value.

Use Cases

This can be used to express type changes as a result of mutating operations, covering some of the use cases of e.g. Rust's affine types. (See also #16148.)

Examples

Consider this example, compiled with --strictNullChecks:

type NonEmptyArray<T> = {
  pop(): T;
} & Array<T>;

function isNonEmpty<T>(array: Array<T>): array is NonEmptyArray<T>;
function isNonEmpty(array: Array<unknown>): boolean {
  return array.length > 0;
}

let array: string[] = ['element'];
if (isNonEmpty(array)) {  // Guard gives 'array' type NonEmptyArray<string>.
  const elem1: string = array.pop();  // Works. This is correct.
  const elem2: string = array.pop();  // Also works, but elem2 will be undefined at runtime!
}

We could make this correct if pop() could both return a value and behave as a type guard. This isn't great syntax, but nonetheless consider if this was supported:

type NonEmptyArray<T> = {
  pop(): T && this is Array<T>;
} & Array<T>;

function isNonEmpty<T>(array: Array<T>): array is NonEmptyArray<T>;
function isNonEmpty(array: Array<unknown>): boolean {
  return array.length > 0;
}

let array: string[] = ['element'];
if (isNonEmpty(array)) {  // Guard gives 'array' type NonEmptyArray<string>.
  const elem1: string = array.pop();  // Returns a string and gives 'array' type Array<string>.
  const elem2: string = array.pop();  // Doesn't compile; pop() returns 'string | undefined'!
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code

This can use a new, previously invalid syntax to avoid affecting any existing program.

  • 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.)

There's no change in the code that's emitted; this feature would exist purely at the level of the type system.

I believe that it would. It seems to be aligned well, in particular, with "Statically identify constructs that are likely to be errors."

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 no especifica ningún archivo fuente, prueba ni punto de entrada del compilador. Comienza localizando el tratamiento que hace TypeScript de los predicados de tipo y los tipos de retorno, y luego define la sintaxis aceptada y el comportamiento de narrowing, incluido el ejemplo mutante de pop(), con pruebas del compilador que cubran los casos nuevos y no válidos.

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.