我有以下几种类型,我在不牺牲类型的情况下试图获取所需的路径。但这会引发以下错误
export interface IProps {
user: any;
car: IVehicle;
}
export interface IVehicle {
kind: String;
color: String;
}
_.get<IProps, 'car.color'>(props, 'car.color');
[ts] Argument of type '"car.color"' is not assignable to parameter of type 'number'.
答案 0 :(得分:1)
如果您想减轻痛苦:
Mean
相反:
const color = props && props.car ? props.car.color : null;
答案 1 :(得分:1)
const color = props?.car?.color;
在 d.ts
文件中,我们有这样的重载:
get<TObject extends object, TKey1 extends keyof TObject, TKey2 extends keyof TObject[TKey1]>(object: TObject, path: [TKey1, TKey2]): TObject[TKey1][TKey2];
所以应该是:
_.get<IProps, 'car', 'color'>(props, ['car', 'color']);
答案 2 :(得分:0)
cart.total_price > 15000
的类型为car.color
。因此用法是:
String