New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Accept de-structured elements in type predicates #41173
Comments
|
Self-contained examples that don't assume importing/knowledge of rxjs would be very helpful |
|
I run into this when filtering the output of If I want all pairs from the query params that are arrays, I currently have to do: or I would prefer to do: |
|
A simple-with-no-external-elements example could be: type X = { value: number | string; };
const xs: Array<X> = [{ value: 42 }, { value: 'hello' }];
// without the feature
const filtered = xs
.filter(({ value }) => typeof value === 'number')
.map(x => x as { value: number })
;
// with the feature
const filtered = xs
.filter(({ value }): value is number => typeof value === 'number')
; |
|
Ran into this problem in React. I have a React context in the form of a class. function assertSomething(
obj: T
): obj is Omit<T, 'property'> & { property: AssertionHere } {
return true;
}in my project as suggested by @rraziel doesn't work. Turns out, since In my project, intellisense reported
In conclusion, it'll be real nice for this feature to be implemented (or this bug to be fixed). |
|
I agree that this is a useful feature and an unfortunate oversight on typescript's part. const filtered = xs
.filter((x): x is { value: number } => {
const { value } = x;
return typeof value === 'number';
});Same goes for array destructuring(my use case which involved rxjs's type X = [ number | string ];
const xs: Array<X> = [[ 42 ], [ 'hello' ]];
// without the feature
const filtered = xs
.filter((x) => {
const [ value ] = x;
return typeof value === 'number';
})
;
// with the feature
const filtered = xs
.filter(([ value ]): value is number => typeof value === 'number')
; |
Search Terms
Suggestion
The possibility to use destructured parameters in type predicates.
Use Cases
Destructuring is heavily used in functional/reactive programming, notably with rxjs where various contextual properties tend to be passed between each operator.
Having the ability to succinctly test for types would make the code more readable, e.g.:
Right now the alternative is
Or, without a predicate
Examples
This would roughly translate to something like:
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: