Search code examples
typescriptlodashtypescript-typings

Typescript all lodash/fp return types are any


I have installed in a typescript project:

"@types/lodash": "4.14.150",
"loadash": "4.17.15",

All of data, when processed through lodash/fp is returned as any

The following code doesn't report any errors:

import {prop} from 'lodash/fp';


const data: { id: string } = { id: 'hello' }

// from the above we know that id is a string, but typing it as a number doesn't report any errors
const meh: number  = prop('id')(data) 

Without adding the type of number, I can see that return type is any

How can I fix this, please? Thanks


Solution

  • According to the typescript typings, the single string argument form of prop() is:

    (path: lodash.PropertyPath): LodashProp8x1;
    

    And LodashProp8x1 is:

    interface LodashProp8x1 {
        (object: null | undefined): undefined;
        (object: any): any;
    }
    

    So prop('id') returns a function that either returns undefined or any.

    It appears that the official typings do not support pulling props out in a type safe way with this call signature.

    If you use one of the generic forms with two arguments, and it works like you expect:

    const meh: number = prop('id', data)
    // Type 'string' is not assignable to type 'number'
    

    Or it looks like there's a generic form for the two function syntax, but you'll have to tell the compiler ahead of time the object type you intend to use:

    const meh: number = prop<typeof data, 'id'>('id')(data)
    // Type 'string' is not assignable to type 'number'