microsoft / microsoft/TypeScript
Suggestion: Allow getters to have predicate return types
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.3k
- Merge medio
- 1 d 19 h
- PR fusionados (30 d)
- 117
Descripción
Suggestion
🔍 Search Terms
getter, 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
This has been requested before (e.g., #6994) but declined because at the time getters were merely an aspect of implementation. Since that is no longer the case, would there be any interest in revisiting the suggestion?
📃 Motivating Example
class Person {
name?: string;
}
class Thing {
constructor(public owner: Person | null = null) {}
get isOwned(): this is Owned<this> {
return !!this.owner;
}
}
type Owned<T extends Thing> = T & { owner: NonNullable<T['owner']> };
💻 Use Cases
I have a use case much like the above. Currently type narrowing by checking thing.owner isn't honored when thing is used as a function argument:
function doSomethingWithOwnedThing(ownedThing: Owned<Thing>) {}
declare const thing: Thing;
if (thing.owner) {
thing.owner.name; // ok
doSomethingWithOwnedThing(thing); // not ok (thing.owner is possibly `null`)
}
With the above, I can create a normal function or method that returns a type predicate or otherwise simply assert that thing is an Owned<Thing>. Given that user-defined type guards are encapsulated type assertions, and getters are shiny and neat, a boolean getter that doubles as a type guard would be nicest.
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Empieza revisando los ejemplos de getters y type guards del issue; después, compara la discusión anterior en #6994 y la discusión de diseño enlazada en #43036. Se considera terminado cuando se acepte el tipo de retorno propuesto para el getter y funcione el estrechamiento de Owned<Thing> demostrado, 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
- Tranquilo
- Claridad
- Bastante claro
- Aptitud para principiantes
- 42/100