Replies: 3 comments
-
It isn't possible so easily. Though it might be possible through writing you own custom type. First of all, start writing the type that will perform this: interface Data {
x: string;
y: string;
}
type SelectIfTrue<O extends object, O1 extends object> =
O.Pick<O, O.SelectKeys<O1, true>>
type t0 = SelectIfTrue<Data, {x: true, y: false}> // works Then, you integrate the type to your function by casting its result: // you will have to use `as const`. so we use a generic parameter
function select<O extends object>(opts: O) {
const data: Data = {} as Data // from somewhere
const o = {}
for (const key in data)
if (opts[key] === true) o[key] = data[key]
return o as SelectIfTrue<Data, O> // casting the result
}
const t1 = select({x: true, y: false}) // not working
const t2 = select({x: true, y: false} as const) // works I find this cumbersome. It is good to try to summarize TypeScript types. Even though this library can allow you to do such computations, you should not try to compute absolutely everything. Instead, your type t2 = O.Optional<Data> |
Beta Was this translation helpful? Give feedback.
-
@pirix-gh Thank you! Perhaps I should be less precise, it just seemed like it would be nice given the strict coupling between input and output. Thanks also for these great tools! 😃 |
Beta Was this translation helpful? Give feedback.
-
Oh, although I notice that at least with the |
Beta Was this translation helpful? Give feedback.
-
🤔 Question
Describe your question
Say we have an interface with some fields:
and a function that takes an object to select fields from that interface:
How could we type the return such that it excludes fields in
Data
that are nottrue
in the options object provided toselect
?Thanks!
Search tags, topics
#typescript #object #filter #exclude
Beta Was this translation helpful? Give feedback.
All reactions