Why Nostr? What is Njump?
2024-06-22 14:49:46
in reply to

Doug Parker 🕸️ on Nostr: Mainly being explicit that a cast is happening. Usually `getData<string>('key')` ...

Mainly being explicit that a cast is happening.

Usually `getData<string>('key')` syntax is constrained such that `string` is validated to be correct. If the data was actually a `number`, I would expect TS to stop me with an error. I think this also applies with `const data: string = getData('key');`. The type `string` causes `getData`'s return type to match automatically in a potentially incorrect way.

Using a cast like `getData('key') as string` makes it clear to the developer that "You are asserting the result is `string`, whether or not it actually is."

If I were reviewing this code, it would also stand out as something which may justify a runtime check (`typeof data === 'string`) in case there's ambiguity in a way I'd be unlikely to notice for `getData<string>`.

This is actually a part of the Google style guide, though it does not include justification unfortunately: https://google.github.io/styleguide/tsguide.html#return-type-only-generics
Author Public Key
npub1hvt595dnyyfx57xf5edvhxuppfykj0qmw6myg6hqt87rluxv90eqdwjhta