Home > Blockchain >  How can I require a parameter to be typed as a union, and not just as a member?
How can I require a parameter to be typed as a union, and not just as a member?

Time:12-14

Consider this example of a function that takes a union type:

const isNull = (value: string | null) => value === null

How can I allow only this kind of usage (where the value is possibly null):

const maybeNull = Math.random() < 0.5 ? 'value' : null

isNull(maybeNull)

While disallowing this (where the value is definitely not null):

const definitelyNotNull = 'value'

isNull(definitelyNotNull) // should error

CodePudding user response:

To do this cleanly you'd need some kind of negated type (see for example issue 4183), which is not possible in TypeScript, but as a workaround you can make isNull generic and validate that null extends the parameter type:

type MaybeNull<T> = null extends T ? T : never

const isNull = <T>(value: MaybeNull<T>) => value === null

This works for the example applications, though the error isn't amazing.

const maybeNull = Math.random() < 0.5 ? 'value' : null

isNull(maybeNull) // Allowed

const definitelyNotNull = 'value'

isNull(definitelyNotNull)
// Error: Argument of type 'string' is not assignable to parameter of type 'never'.

TypeScript playground

  • Related