js-lib icon indicating copy to clipboard operation
js-lib copied to clipboard

feat: Adding RequireProp type helper

Open fiddur opened this issue 4 months ago • 4 comments

Helpful type to require one property in a type. Could be used like

  const changeEntries = dailyEntries.entries.filter(
    (e): e is RequireProp<Entries, 'change'> => !!e.change,
  )

...to allow accessing the entry.change property later without warning about Could be undefined.

fiddur avatar Oct 06 '25 13:10 fiddur

Not sure about naming here. Could be RequiredProp (rather than require...). Or RequiredPick since we are picking one property.

fiddur avatar Oct 06 '25 13:10 fiddur

Not seeing how this would be used, I say LGTM, but in my experience Kirill has opinions on being too precise with types, so I'll defer to him.

If it's an internal, one-off thing somewhere in our helpers ✅ But if other developers can face both versions of DailyEntries - one with optional and one with the required property -, then I'd probably create a new named interface/type. (Of course, we can create a new named interface/type using this helper too, which would be okay too.)

I like the RequiredProp name - from all the other options you mentioned. I wonder about making it accept more than one key though, e.g. RequiredProps, or WithRequiredProps.

mrnagydavid avatar Oct 07 '25 08:10 mrnagydavid

I was using it in a filter rule and then wanting to use the filtered data without checking again or using the non-null assertion operator !

fiddur avatar Oct 07 '25 08:10 fiddur

Actually right now I don't need it anymore (change of solution), but I have used this previously and find it useful to avoid the !.

fiddur avatar Oct 07 '25 09:10 fiddur

Merging this, as it would make some non-null assertions not needed in https://github.com/NaturalCycles/NCBackend3/pull/11426

fiddur avatar Dec 09 '25 08:12 fiddur

:tada: This PR is included in version @naturalcycles/js-lib-v15.54.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

github-actions[bot] avatar Dec 09 '25 08:12 github-actions[bot]