TypeScript: Add typing to the lodash keys helper

With lodash (Version 4.17.21 at time of writing) and @types/lodash (Version 4.14.191 at time of writing) using the keys helper will lose the type information of the given object.

// test object upon which we will call keys
type TObject = {
  fieldNum: number;
  fieldStr: string;
  fieldBln: boolean;
  fieldArr: string[];
}

const o: TObject = {
  fieldNum: 42,
  fieldStr: 'greladesign',
  fieldBln: true,
  fieldArr: ["a", "b", "c"]
};

const keysOfObject = keys(o); // tooltip will show: const keysOfObject: string[]

//
keysOfObject.forEach((field /* :string */): void => {
  // You have lost the information about keys of the object, 
  // TypeScript will no longer be able to verify field for you
  if (field === 'fieldBoolean') { // TS will accept this incorrect field name
    const flag = o[field]; // TS will use any here
  }
})

Code language: TypeScript (typescript)

As you can see this is not very useful, luckily it is easy to resolve

// add following to your typings e.g. lodash-override.d.ts
export {};

declare module 'lodash' {
  interface LoDashStatic {
    keys<O>(object?: O): (keyof O)[]; 
  }
}
Code language: TypeScript (typescript)

With this module augmentation the TS will now properly identify misspelled field name and will give a nice warning: "This condition will always return 'false' since the types 'keyof TObject' and '"fieldBoolean"' have no overlap.” or "This comparison appears to be unintentional because the types 'keyof TObject' and '"fieldBoolean"' have no overlap.".

Source code

This entry was posted in TypeScript and tagged . Bookmark the permalink.

1 Response to TypeScript: Add typing to the lodash keys helper

  1. Pingback: TypeScript: Add typing to the lodash entries helper | blog.greladesign

Comments are closed.