SCM
SCM

Reputation: 55

Typescript generic type but not string or any

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

Answers (2)

tenshi
tenshi

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.

Playground

Upvotes: 2

protob
protob

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

Related Questions