I
I
Incold2022-02-09 20:12:36
typescript
Incold, 2022-02-09 20:12:36

Why is the type formed incorrectly?

Hello! I ran into a problem with component typing
Typing component props:

// Основная проблема в этом типе
type FunctionParams<U> = U extends undefined
  ? {
      page: number;
      limit: number;
    }
  : {
      page: number;
      limit: number;
    } & U;

interface IProps<T, U> {
  queries?: U;
  getList: (
    props: FunctionParams<U>
  ) => AxiosPromise<IAxiosPaginatedResponse<T>>;
  ...
}


Call example:
const filters = {
   search:  '';
   city: 1;
 };
  <Pagination
       getList={getList}
       queries={filters}
       ...
   />


getlist function:
export const getList = (props: {
  page: number;
  limit: number;
  search: string;
  city: number;
}): AxiosPromise<IAxiosPaginatedResponse<IListItem>> => {
  return ...
};


The task is to match the number (and types) of props passed to the function, i.e. as part of the example, so that search and city must be passed to queries, otherwise throw an error.
However, when passing an extra property to queries or if you comment out the transfer of queries, the error does not appear, instead (in ide) the getList prop type is converted to:
If queries are not passed
(props: ({page: number, limit: number} & {page: number, limit: number, search: string, city: number}) => ...

If you pass an extra property to queries, for example, newProp: string
(props: ({page: number, limit: number} & {newProp: string, search: string, city: number}) => ...


Why does the conditional type not work in the first error (if U automatically generates the type from the function parameters, then how to avoid this, in other words, how to write the check correctly), and in the second one does not swear at an extra property?

Thanks in advance for any help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WbICHA, 2022-02-10
@Incold

After many iterations, together with Aetae , we came up with this relatively beautiful solution:
https://www.typescriptlang.org/play?keyofStringsOn...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question