Reputation: 863
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`
Upvotes: 4
Views: 463
Reputation: 67860
With a similar idea than Nadia's answer, this should also work (playground):
type Test<T extends (null extends T ? unknown : never)> = T
Upvotes: 4
Reputation: 5036
This seems to work for your case: type Test<T extends (U extends null ? T : unknown), U = T extends null ? T:never>={}
Upvotes: 4