Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash get with correct types

I have following types which I'm trying to get the required path without sacrificing the type. But it throws the following error

export interface IProps {
  user: any;
  car: IVehicle;
}

export interface IVehicle {
 kind: String;
 color: String;
}

_.get<IProps, 'car.color'>(props, 'car.color');

Error

[ts] Argument of type '"car.color"' is not assignable to parameter of type 'number'.

like image 446
user1595858 Avatar asked Oct 27 '25 04:10

user1595858


2 Answers

car.color is of type String. So the usage would be:

_.get<IProps, String>(props, 'car.color');

like image 165
user10923870 Avatar answered Oct 29 '25 19:10

user10923870


From TypeScript 3.7 you can use Optional chaining

const color = props?.car?.color;

Lodash _.get

In d.ts file we have such overloading:

get<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof TObject[TKey1]>(object: TObject, path: [TKey1, TKey2]): TObject[TKey1][TKey2];

So it should be:

_.get<IProps, 'car', 'color'>(props, ['car', 'color']);
like image 24
Vadim Petrov Avatar answered Oct 29 '25 19:10

Vadim Petrov