You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
interfaceData{x: string;y: string;}typeSelectIfTrue<Oextendsobject,O1extendsobject>=O.Pick<O,O.SelectKeys<O1,true>>typet0=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 parameterfunctionselect<Oextendsobject>(opts: O){constdata: Data={}asData// from somewhereconsto={}for(constkeyindata)if(opts[key]===true)o[key]=data[key]returnoasSelectIfTrue<Data,O>// casting the result}constt1=select({x: true,y: false})// not workingconstt2=select({x: true,y: false}asconst)// 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 select should spit a simpler type out:
@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! 馃槂
Oh, although I notice that at least with the strict compiler option the as const assertion isn鈥檛 necessary, which was the main thing I disliked as it鈥檚 user-facing. Nice! Thanks again for your help.
馃 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
The text was updated successfully, but these errors were encountered: