代码之家  ›  专栏  ›  技术社区  ›  user1595858

正确类型的lodash get

  •  0
  • user1595858  · 技术社区  · 6 年前

    我有以下类型,我试图在不牺牲类型的情况下获得所需的路径。但它抛出了以下错误

    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'.

    2 回复  |  直到 6 年前
        1
  •  1
  •   Daniel Khoroshko    6 年前

    如果你想减轻疼痛:

    const color = props && props.car ? props.car.color : null;

    面向方面的:

    (typeof props)["car"]["color"]

        2
  •  0
  •   user10923870    6 年前

    car.color 属类型 String . 所以用法是:

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