-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Open
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
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.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript