Reputation: 55
I have a generic function that looks like this:
private getItem<T>(identifier: string): T {...}
Now I want to change this, so that the return type can be any object or array, but not any and also not string. I'm unsure how to achieve that.
Upvotes: 2
Views: 528
Reputation: 26317
If you want to disallow the use of any
, you'll need a little more magic. Using a type from this question to check for any
, we can then use something like
type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N;
declare function foo<T extends IfAny<T, never, object>>(): T;
If T
is any
, then the constraint is never
, otherwise, the constraint is object
.
Upvotes: 2
Reputation: 3583
T extends object
can be use for objects and arrays, but not primitives and any:
private getItem<T extends object>(identifier: string): T {...}
Upvotes: 0