2

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.

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

the current playground shows "Type parameter 'T' has a circular constraint". Probably an update in ts since this was written
0

T extends object can be use for objects and arrays, but not primitives and any:

private getItem<T extends object>(identifier: string): T {...}

2 Comments

This does not protect against any: tsplay.dev/Wvq8Qm
you got that right

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.