microsoft / microsoft/TypeScript

Asynchronous type guards and assertion signatures

Abierto
#37,681 12 comentarios 205 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

async, asynchronous, promise, type guards, assertion signatures, asserts

Suggestion

TypeScript currently supports user-defined type guards and assertion signatures.

function isCustomType(value: unknown): value is CustomType {
    // ...
}

function assertIsCustomType(value: unknown): asserts value is CustomType {
    // ...
}

I think it would be great if we could also define custom asynchronous type guards and assertions.

async function isCustomType(value: unknown): Promise<value is CustomType> {
    // ...
}

async function assertIsCustomType(value: unknown): Promise<asserts value is CustomType> {
    // ...
}

Use Cases

This feature would allow to check types and validate data asnychonously. Please look at the examples below.

Examples

Imagine the code like this:

interface User {
    name: string;
}

type Valid<T> = T & {
    readonly $valid: unique symbol;
}

async function createUser(user: User): Promise<void> {
    validateUser(user);
    await saveValidUserToDatabase(user);
}

function validateUser(user: User): asserts user is Valid<User> {
    if (user.name.length < 5) {
        throw new Error('User name must be at least 5 characters long');
    }
}

async function saveValidUserToDatabase(user: Valid<User>): Promise<void> {
    // ...
}

But sometimes, validation is done asynchronously, e.g. on server-side. Currently, you can achieve it this way:

async function createUser(user: User): Promise<void> {
    await validateUser(user);
    await saveValidUserToDatabase(user as Valid<User>);
}

async function validateUser(user: User): Promise<void> {
    // ...
}

But if TypeScript supported asynchronous assertions, you could skip as Valid<User> type assertion and let the TS do the job:

async function createUser(user: User): Promise<void> {
    await validateUser(user);
    await saveValidUserToDatabase(user);
}

async function validateUser(user: User): Promise<asserts user is Valid<User>> {
    // ...
}

Exactly the same issue could be presented for user-defined type guards.

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 revisando el manejo existente de TypeScript de los type guards definidos por el usuario y las firmas de aserción en el compilador y el comprobador de tipos. Define el comportamiento de los guards y las aserciones asíncronos, incluido cómo afecta await al estrechamiento de tipos, y después añade pruebas del compilador que cubran las firmas basadas en Promise propuestas y los tipos de control de flujo resultantes.

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.