-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Conditionally filter types from tuples at transpilation time. #38044
Comments
What does "remove a type from an object" mean? |
I'm guessing you want this type Step1<T> = { [K in keyof T]: T[K] extends boolean ? never : K }[keyof T];
type FilterBooleans<T> = { [K in Step1<T>]: T[K] }
// { s: string, n: number }
type RecordWithoutBooleans = FilterBooleans<{ s: string, b: boolean, n: number }>; The corresponding thing for tuples is kind of conceptually weird since it implies some kind of splicing operation? |
@RyanCavanaugh Thanks for the suggestion, I see that works for records but not tuples. If I run: FilterBooleans<[string, boolean, Date, boolean]>; I get a type like this (the tuple has been converted into a record): interface TupleWithoutBooleans {
4: undefined;
0: string;
2: Date;
} I need it for my parser generator though, so I can build a parser from component functions. const parseRule = parseSequence(parseRuleName(), notPredicate(parseConstant("<")) The |
@RyanCavanaugh This is labelled "Waiting for feedback" but I'm not sure what feedback you'd like, could you let me know? BTW in typescript 4.1 I can do this: type NoBoolean<K, T> = T extends boolean ? never : K
type FilterBooleans<T> = {
[K in keyof T as NoBoolean<K, T[K]>]: T[K]
}
type Filtered = FilterBooleans<[string, boolean, number, boolean]> Here type type FilterBooleans<T> = [
[K in keyof T as NoBoolean<K, T[K]>]: T[K]
]; (i.e. the same as above but with the |
Closing in favour of #42122 |
@insidewhy: The
|
Search Terms
tuple, filter, metaprogram
Suggestion
I'd like a better way to filter types from a tuple type (or indeed object type). Currently I can easily make a type not optional (with
-?
) or make one optional (?
) but I can't conditionally remove a type element from a tuple to produce another tuple. Well actually I can, with this crazy metaprogram that uses up so much CPU that it isn't usable in the real world:Use Cases
I am writing a parser library where you can build parsers by composing operators (each operator being a higher order function). When composing a parser using the sequence operator, the return type of the sequence should be a tuple of the return types of each operator the sequence is composed from. However the return types of "predicate" operators should be excluded from the tuple return type since the predicate operators don't parse any data, they only match or fail to match.
Examples
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: