Middle+
How to make a function with a Generic accept only a string or an instance of class Bar, and throw a TypeScript error in other cases?
sobes.tech AI
Answer from AI
In TypeScript, you can restrict a generic parameter using conditional types and union types. To make a function accept only either a string or an instance of the Bar class, you can do the following:
class Bar {
// ...
}
function foo<T extends string | Bar>(arg: T): void {
// the function accepts only string or Bar
}
foo('hello'); // OK
foo(new Bar()); // OK
foo(123); // compile error
If you need stricter control, for example, to prevent subclasses of Bar, you can use T extends string | Bar and check the type inside the function.
You can also use function overloads:
overload function foo(arg: string): void;
function foo(arg: Bar): void;
function foo(arg: any): void {
// implementation
}
This will allow TypeScript to give an error when an incompatible type is passed.