microsoft / microsoft/TypeScript

Support `!==` operator in `is` and `asserts` return type syntax

Abierto
#55,813 3 comentarios 1 reacción 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

unknown, assert, narrow, undefined, "is not"

✅ 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 feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
⭐ Suggestion

This looks like something that would have been asked before, but it's hard to search for.

Right now asserts is a pretty magical syntax that lets you do:

function assert(proposition: unknown): asserts proposition {
    if (!proposition) {
        throw new Error()
    }
}

function foo(value: unknown): {} | null {
    assert(value !== undefined);
    return value;
}

However, trying to express a more specialized function doesn't work

function assertNotUndefined<T>(value: T): asserts value is Exclude<T, undefined> {
    if (value === undefined) {
        throw new Error();
    }
}

function foo(value: unknown): {} | null {
    assertNotUndefined(value);
    return value;  // Doesn't work
}

This is because Exclude<unknown, undefined> is still just unknown, since unknown is not just an alias for {} | null | undefined. Assuming that won't change, how else can one express assertNotUndefined? Well, if we take the original assert function and try to retroactively rationalize its syntax as this

function assert(proposition: unknown): asserts proposition;

when called as

assert(proposition !== undefined)

(hand-waving) just specializes to this

function assert(proposition: unknown): asserts proposition !== undefined;

I don't care to bikeshed over whether the syntax should be asserts proposition is not undefined, whether the LHS or RHS operands can be flipped, whether != or other operators should exist, or if any type expressions other than primitive literals like undefined should be supported, so I'll leave that to the comments.

📃 Motivating Example
function assertNotUndefined(proposition: unknown): asserts proposition !== undefined;

function foo(value: unknown): {} | null {
    assertNotUndefined(value);
    return value;  // Works!
}
💻 Use Cases
  1. What do you want to use this for?
    A function that can exclude undefined can be composed with other functions, e.g. array.filter(isNotUndefined)
  2. What shortcomings exist with current approaches?
    There's no clean way to define such a function without ugly conditionals to handle unknown.
  3. What workarounds are you using in the meantime?
    Rewrite code in more verbose style, e.g. manually construct a new array using a for loop instead of array.filter.

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 los ejemplos motivadores de la issue y compara la sintaxis de aserción !== propuesta con la sintaxis existente de tipos de retorno con is y asserts. El alcance de los operadores y las expresiones de tipos compatibles no está resuelto intencionadamente, por lo que completar esto requeriría establecer la sintaxis y la semántica, implementar el estrechamiento de tipos y añadir una cobertura adecuada 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
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.