Typescript: Allow any type except specific values
Typescript doesn’t have a simple type to describe the relation “allow any type except the string literals "foo"
and "bar"
”. However, a small generic interjeciton type will enable Typescript to understand what you mean:
type Disallowed = "foo" | "bar";
type Input<T> = T & (T extends Disallowed ? never : T);
// Any input is valid except for the string literals "foo" and "bar"
function snafucate<T>(input: Input<T>) {...}