Home > Mobile >  Typescript type safe function params
Typescript type safe function params

Time:12-09

Is it possible to make the filterValue param (which depends on the type of the GitHubRepositoryFilter key) type safe?

export type GitHubRepositoryFilter = {
  withName?: string;
  withWorkflowRuns?: boolean;
};

export const repositoryFilters: Record<
  keyof GitHubRepositoryFilter,
  (repository: GitHubRepository, filterValue: any) => boolean
> = {
  withWorkflowRuns: ({ hasWorkFLows }, filterValue) => hasWorkFLows === filterValue,
  withName: ({ name }, filterValue) => name.toLowerCase().includes(filterValue.toLowerCase()),
};

CodePudding user response:

You can use a mapped type:

export type GitHubRepositoryFilter = {
  withName?: string;
  withWorkflowRuns?: boolean;
};

type GitHubRepositoryFilters = {
  [K in keyof GitHubRepositoryFilter]: (
    repository: GitHubRepository,
    filterValue: GitHubRepositoryFilter[K]
  ) => boolean
};

export const repositoryFilters: GitHubRepositoryFilters = {
  withWorkflowRuns: ({ hasWorkFlows }, filterValue)
    => hasWorkFlows === filterValue,
  withName: ({ name }, filterValue)
    => name.toLowerCase().includes(filterValue?.toLowerCase()),
};
  • Related