Yes, I absolutely agree with you. For static paths, it's definitely better to prefer regular field access with an optional chaining. However, _.get is still widely used, and some might find it easier to replace a function call or augment lodash typings.
Speaking of type-casting, in the first place, you want to avoid it as much as possible. This thing makes type checking looser, and after all, that's not why we are enabling strict flag, right? In this particular case, you are giving TS a hint that this any is a more specific type. But get anyway returns any, and if for some reason type of address.street changes, TS will not complain. In the end, any could be cast to literally any type.
Regarding dynamic paths, of course, not every case is covered (and GetFieldType should probably return unknown when the field is not found). But this approach still works when you have a union of possible values
typeLetter='alpha'|'beta'|'gamma'constsymbols={alpha:{symbol:'α'},beta:{symbol:'β'},}functiongetSymbol(letter:Letter){returnsymbols[letter]?.symbol// TS error: Property 'gamma' does not exist on type}functiongetSymbolWithPath(letter:Letter)/* : string | undefined */{returngetValue(symbols,`${letter}.symbol`)}
And anyway, you could think of this article as an exercise to better understand template literal and conditional types 🙂
As for a real-life scenario, we use it in a slightly different, a bit less dynamic way, to create strongly-typed APIs similar to react-table columns config. But that's a topic for another article 😉
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Yes, I absolutely agree with you. For static paths, it's definitely better to prefer regular field access with an optional chaining. However,
_.get
is still widely used, and some might find it easier to replace a function call or augment lodash typings.Speaking of type-casting, in the first place, you want to avoid it as much as possible. This thing makes type checking looser, and after all, that's not why we are enabling
strict
flag, right? In this particular case, you are giving TS a hint that thisany
is a more specific type. Butget
anyway returnsany
, and if for some reason type ofaddress.street
changes, TS will not complain. In the end,any
could be cast to literally any type.Regarding dynamic paths, of course, not every case is covered (and
GetFieldType
should probably returnunknown
when the field is not found). But this approach still works when you have a union of possible valuesAnd anyway, you could think of this article as an exercise to better understand template literal and conditional types 🙂
As for a real-life scenario, we use it in a slightly different, a bit less dynamic way, to create strongly-typed APIs similar to
react-table
columns config. But that's a topic for another article 😉