6 ms·
Throw in an eslint rule to disallow ! outside of tests, you won't regret it
by dtech 5y ago
Throw in an eslint rule to disallow ! outside of tests, you won't regret it
- dmitryminkovsky 5y agoUnfortunately I have some spots where it’s unavoidable due to generated types that I can’t control being not quite right. It’s sad! Yes, otherwise I’d never use it, or far more sparingly (sometimes it is “correct”, though with effort it can be avoided)
- renke1 5y agoI have a utility function that I use for cases where I know for sure that a value is defined: export function assertIsDefined<V>( value: V, buildMessage = defaultAssertIsDefinedMessage ): asserts value is NonNullable<V> { if (value === undefined || value === null) { throw new Error(buildMessage(value)); } } It would prevent follow up errors if the value in fact was not defined.
- dmitryminkovsky 5y agoYeah I could definitely do this, and maybe should. But the issue is so systemic due to the bad generated types that this would cloud the code without much added benefit.
- renke1 5y agoI had my own share of problems with generated code, so I feel you. I often use that utility when I have some type where under certain condition a value will always be defined, but a union type would make it too complex to be useful.
- dmitryminkovsky 5y agoYeah in my case I am using Postgres via Hasura, which exposes the Postgres DB via a GraphQL API, which in turn can be used to generate types. Unfortunately the nullability of fields in a Postgres view cannot be determined, so all fields in the corresponding types are nullable [0], even if they aren’t in the actual underlying table. So I end up using ! a lot because I know the field is non null in Postgres. It’s a unfortunate. [0] https://github.com/hasura/graphql-engine/issues/1965 https://github.com/hasura/graphql-engine/issues/1965