microsoft / microsoft/TypeScript

Allow composite values to be used in type predicates

Abierto
#43,640 2 comentarios 0 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
1 d 19 h
PR fusionados (30 d)
117

Descripción

Allow composite values to be used in type predicates

🔍 Search Terms

Is, composite type, complex type, composite value, complex value, type predicate, type guard

✅ 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

Type predicates allow you to define functions that can tell the TypeScript compiler if a parameter is of a certain type.
I suggest that this be extended to allow type predicates to narrow the type of composite objects involving parameters.
That is, the left-hand-side of is types should be allowed to include object literals.

📃 Example

Say you have a type that involves a subset of another type:

type MyType = {property1: "static text", property2: "Hello" | "World"};

A type predicate for this would always require passing in the property1 property, even though it’s unnecessary.
Now, you can create a type predicate that only takes the value of property2, but still gurantees the result type:

function foo(text: string): {property1: "static text", property2: text} is MyType {
    return ["Hello", "World"].includes(text);
};

I’ve run into the problem of being unable to do this while developing my website.
I had a tagged union:

type A = {t: "A", value: "X" | "Y"};
type B = {t: "B", value: string};
type U = A | B;

And I wanted to get a value of type A from user input, but default back to a B type if the value wasn’t
To do this, I hoped to be able to do this:

function zit(x: string): {t: "A", value: x} is A {
    return ["X", "Y"].includes(x);
};
function gob(x: string): U {
    return zit(x) ? {t: "A", value: x} : {t: "B", value: x};
};

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

No se nombran archivos, pruebas ni puntos de entrada. Empieza revisando los ejemplos de predicados de tipo del issue y el comportamiento existente del compilador respecto a los protectores de tipo; el cambio estaría completo cuando se acepten tipos de objeto compuestos en los predicados y funcionen los escenarios de narrowing mostrados sin cambiar el JavaScript emitido.

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.