简体   繁体   中英

How to return single type from function

I'm trying to to build a helper function in Typescript (React). I defined a function that return a object or object[] based on the response data.

Now when i use the function the return type is T | T[] T | T[] and this needs to be T or T[] based on the data.

My helper function

import { useQuery } from '@apollo/react-hooks';
import { flatMap } from 'lodash';

export default function QueryHelper<T> (document: any, variables?: {}) {
  const { data: responseData, loading, error } = useQuery(document, { variables });

  const object = (): T => responseData;
  const array = (): T[] => flatMap(responseData);
  let data;

  if (flatMap(responseData).length === 1) {
    data = object();
  } else {
    data = array();
  }
  return { data, loading, error };
}

Call to the function

const objects = QueryHelper<Object>(multipleObjectsDocument); 
const object = QueryHelper<Object>(singleObjectDocument, { id });

return types

const Object: {
    data: Object| Object[]; // This needs to be 1 type
    loading: boolean;
    error: ApolloError | undefined;
}

The main idea is that i can call for example;

const name = object.data.name';
const listOfName = objects.data.map(obj => obj.name);

now i get the following error Property 'map' does not exist on type 'Object | Object[]'. Property 'map' does not exist on type 'Object | Object[]'.

i also tried to conditionally return different variables bases on a if statement but this returns;

const Object: {
    object: Object;
    loading: boolean;
    error: ApolloError | undefined;
} | {
    array: Object[];
    loading: boolean;
    error: ApolloError | undefined;
}

Just fixed it.

export default function QueryHelper<T> (document: any, variables?: {}): queryResponse<T> {
  const { data: responseData, loading, error } = useQuery(document, { variables });
  let data = responseData ?? [];

  const array = flatMap(data);

  if (!loading && array.length === 1) {
    data = array[0];
  } else {
    data = array;
  }

  return { data, loading, error };
}

calls

const objects = QueryHelper<Object[]>(MultipleObjectsDocument).data; // returns type Object[]
const object = QueryHelper<Object>(ObjectDocument, { id }).data; // returns type Object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM