Typescript: returnType based on value 'single' prop

41 Views Asked by At

I'm going to try to explain this as best as I can with a simplified version of my function:

I have this function where I fetch data from a third-party API. Based on the 'single' prop the returned value will either be an a single table object or an array of table objects.

I put a generic value on table prop and single prop. But it seems like this doesn't work with how the function is set up at the moment. My goal is to explain that when single is true, it will just return an object of a table and when single is false it will be an array of table objects. What should be changed?

function useData<T extends TableNames, S extends boolean>({
  query: { table, select = [], filters = [], single = false, limit },
}: UseDataProps<T, S>): UseDataReturn<T, S> {
  const { data } = getData();

  return {
    data: data[table],
  };
}

interface UseDataProps<T, S> {
  query: {
    table: T;
    select?: string[];
    filters?:string[];
    single?: S;
    limit?: number;
  };
}

interface UseDataReturn<T, S> {
  data: S extends true ? Table<T> : Table<T>[];
}

On the single prop I currently get an error like this:

Type 'boolean' is not assignable to type 'S'. 'boolean' is assignable to the constraint of type 'S', but 'S' could be instantiated with a different subtype of constraint 'boolean'.

0

There are 0 best solutions below