Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to constrain generic to a union?

Does anybody know how to express: "constrain the generic so it must be a union with a certain type (in this case: null)"?

type Test<value_T extends Enforce_null_union>

Test<number | null> // Valid
Test<string | null> // Valid
Test<number> // Invalid, must be a union containing `null`
Test<number> // Invalid, must be a union containing `null`
like image 950
user1543574 Avatar asked Oct 20 '25 00:10

user1543574


1 Answers

With a similar idea than Nadia's answer, this should also work (playground):

type Test<T extends (null extends T ? unknown : never)> = T

We can see a pattern here: T extends S -> T extends (validation ? S : never)

With S = unknown if we don't want any particular constraint on T (other that meeting the validation).

like image 107
tokland Avatar answered Oct 26 '25 19:10

tokland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!