Home > Enterprise >  Typescript - Limit keyof to strings
Typescript - Limit keyof to strings

Time:10-16

I am trying to create a filter hook, and I want the arguments to the hook to be the data array, the prop that is going to be filtered (filterProp), and the search text.

So I want the data to be T[], the filterProp to be a string representing one of the keys of T, but only string values (so I can do "toUpper" and "indexOf" on them in the filtering. The search text is just a string.

So I tried something like this::

export const useFilter = <T, K extends Extract<keyof T,string>>(
  data: T[] | undefined,
  filterProp: K,
  searchText: string
) => {

But when I try to "toUppercase" it with it:

data?.filter((item) => item[filterProp].toUpperCase().indexOf(searchText.toUpperCase()) > -1) ?? [];

It comes up with toUppercase does not exist on type 'T[K]'.

Anybody know how I can limit filterProp to a string value representing one of the string keys of T?

Thanks

CodePudding user response:

You could constraint T to have K property with string value:

export const useFilter = <T extends Record<K, string>, K extends PropertyKey>(...

Playground


Links to utils: Record<Keys, Type>, PropertyKey

  • Related