ThomasReggi
ThomasReggi

Reputation: 59345

Match "any" but not array

I am trying to have a function typed to return any but not an array.

Something like this:

Not<any, any[]>

interface Specific {
  name: string;
}

const makeOneCore = (): any => {
  return {};
};

const makeManyCore = (): any[] => {
  return [{}];
};

const makeOne = (): Specific => {
  return makeOneCore();
};

const makeMany = (): Specific[] => {
  return makeManyCore();
};

const makeManyShouldFail = (): Specific[] => {
  return makeOneCore();
};

I would like to type makeOneCore so that makeManyShouldFail would be a typescript error, because it should matches any as being a possible array.

Looking for some way that hello is valid and boom is not.

type NotArray<T> = T extends Array<any> ? never: T;

type v = NotArray<Array<any>>;

const hello: v = {};
const boom: v = [];

console.log({ hello, boom });

Upvotes: 2

Views: 282

Answers (1)

Przemyslaw Jan Beigert
Przemyslaw Jan Beigert

Reputation: 2486

Try something like this

type NotArray<T> = T extends Array<any> ? never: T;

type A = NotArray<Array<any>>; // never
type B = NotArray<Array<string>>; // never
type C = NotArray<boolean>; // boolean

type never can to be assign to any other type

Upvotes: 3

Related Questions