Home > Enterprise >  Lower case object values in typescript?
Lower case object values in typescript?

Time:12-08

Is there any way in typescript to specify that this function will return an object and object values will be a lower case?

This is what I have for now:

const lowercaseObjValues = <T extends Record<keyof T, string>>(
  obj: T
) => {
  return Object.keys(obj).reduce((acc: T, key: string) => {
    acc[key] = obj[key].toLowerCase();
    return acc;
  }, {} as T);
};

CodePudding user response:

This sort of function will only really be helpful if the string values are statically known.

// helper function to add types to Object.entries
const entries = Object.entries as <T>(obj: T) => [keyof T, T[keyof T]][];

type LowercaseValues<T extends Record<string, string>> = { [K in keyof T]: Lowercase<T[K]> };

const lowercaseValues = <T extends Record<string, string>>(obj: T): LowercaseValues<T> =>
  entries(obj).reduce((acc, [key, value]) => {
    // i'm sure this explicit `any` can be removed but it can be left as an
    // exercise for the reader
    acc[key] = value.toLowerCase() as any;
    return acc;
  }, {} as LowercaseValues<T>);

const test = { a: 'UPPER' } as const;
const out = lowercaseValues(test);

declare const assert: <T>(a: T) => void;

assert<'UPPER'>(test.a);
assert<'upper'>(out.a);

TypeScript playground

  • Related