microsoft / microsoft/TypeScript

Aggregate function assertions

Abierto
#42,253 6 comentarios 32 reacciones 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

Suggestion

🔍 Search Terms

Multi-assertions, function assertion signatures, type assertions, aggregate assertions

✅ Viability 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, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Allow functions that assert a type or condition to assert multiple types or conditions

(Maybe?) Allow functions with "asserts" signatures to return a type other than void.
(Update: the secondary goal is covered by other issues)

💻 Use Cases

It allows multiple type assertions at once.

// declare AssertionError

function assert(x: unknown, y: unknown): (asserts x is number) & (asserts y is number) {
    if (typeof x !== "number" || typeof y !== "number") {
        throw new AssertionError("Assert failed: 'x' and 'y' are not both numbers");
    }
}

or

function safeAdd(x: unknown, y: unknown): (number) & (asserts x is number) & (asserts y is number) {
    if (typeof x !== "number" || typeof y !== "number") {
        throw new AssertionError("`x` and `y` are not both numbers");
    } else {
        return x + y;
    }
}

or

declare function safeAdd(...args: unknown[]): asserts args is [number, number];

No idea what the syntax would be, but this should give the idea.

📃 Motivating Example

My use for this was that I had a function that accepted two parameters. It only operated if the first parameter was of a type (T), it also had an overload for the second parameter being the same type (T) or anything else.

declare function assertIsT (x: unknown): asserts x is T;
declare function isT (x: unknown): x is T;
function f (x: unknown, y: unknown): asserts x is T;
function f (x: T, y: T | H) {
    assertIsT(x);
    // x: T

    if ( isT(y) ) {
        // ... y: T
    } else {
        // ... y: H
    }
}

This was meant to be "JavaScript-compatible" code, as in, it could be used by a non-TS user with relative type safety, but, the assertion seems like extra work, as if I'm being over-cautious, so I wanted to simplify it:

declare function isT (x: unknown, y: unknown): (asserts x is T) & (y is T);
function f (x: unknown, y: unknown): asserts x is T;
function f (x: T, y: T | H) {
    if ( isT(x, y) ) {
        // ... x: T
        // ... y: T
    } else {
        // ... x: T
        // ... y: H
    }
}

Now, it's terse and straightforward, while retaining type-safety.
(I am not advocating any specific syntax for the aggregation/mixing)

I tried to get this to work with function overloads, but it wasn't happening.
Playground link


Related issues?
https://github.com/microsoft/TypeScript/issues/40562
https://github.com/microsoft/TypeScript/issues/34636

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 de assertion-signature y la reproducción enlazada en Playground; después, lee las issues relacionadas 40562 y 34636. Determina la sintaxis prevista y el comportamiento de la comprobación de tipos al combinar assertions, incluida la tuple assertion propuesta; se considera terminado cuando se hayan resuelto las implicaciones para el diseño del lenguaje y la compatibilidad.

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
Necesita aclaración
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.