开发者问题收集

未捕获的类型错误:无法设置未定义的属性“索引”

2021-07-29
619

我正在尝试执行的操作如下:

interface VehicleSeatData {
    index: number;
    positions: Vector3Mp;
}

interface VehicleSeat {
    [key: string]: VehicleSeatData;
}

getSeatData(vehicle: VehicleMp): VehicleSeat | null {
        if(!vehicle) {
            return null; 
        }

        let seats: VehicleSeat = {};

        seats['seat_r'].index = vehicle.getBoneIndexByName('seat_r');
        seats['seat_pside_f'].index = vehicle.getBoneIndexByName('seat_pside_f');

        seats['seat_r'].positions = vehicle.getWorldPositionOfBone(seats['seat_r'].index);
        seats['seat_pside_f'].positions = vehicle.getWorldPositionOfBone(seats['seat_pside_f'].index);

        return seats;
    }

我得到的错误是:

Uncaught TypeError: Cannot set property 'index' of undefined

我不确定我哪里做错了,我读过的所有内容(到目前为止)都告诉我我走在正确的方向上。这不可能吗?

2个回答

您将 seats 初始化为一个空对象。 let seat = { 。 然后您访问 seats.seat_r (与 seats['seat_r'] 相同),其默认值为 undefined 。之后,您尝试访问其 index 属性,但该属性不存在 ( undefined.index -> property 'index' of undefined )。

为了解决这个问题,您必须将 seats 的每个属性设置为 VehicleSeatData 类型的空版本。

  let seats: VehicleSeat = {
    'seat_r': {
      index: undefined,
      positions: undefined,
    },
    'seat_pside_f': {
      index: undefined,
      positions: undefined,
    },
    'seat_r': {
      index: undefined,
      positions: undefined,
    },
    'seat_pside_f': {
      index: undefined,
      positions: undefined,
    },
  };
  
  // It is also enough to just initialize the properties as an empty object:
  // let seats: VehicleSeat = {
  //   'seat_r': {},
  //   'seat_pside_f': {},
  //   'seat_r': {},
  //   'seat_pside_f': {},
  // };
  

  // Now you can access the properties and set its sub-properties.
  seats['seat_r'].index = vehicle.getBoneIndexByName('seat_r');
  seats['seat_pside_f'].index = vehicle.getBoneIndexByName('seat_pside_f');

  seats['seat_r'].positions = vehicle.getWorldPositionOfBone(seats['seat_r'].index);
  seats['seat_pside_f'].positions = vehicle.getWorldPositionOfBone(seats['seat_pside_f'].index);

这也意味着您可能必须将类型从

interface VehicleSeatData {
  index: number;
  positions: Vector3Mp;
}

更改为

interface VehicleSeatData {
  index?: number;
  positions?: Vector3Mp;
}

因为在此示例中,这些属性可能未定义,直到您正确设置它们。

Philipp Meissner
2021-07-29

VehicleSeatData 没有任何属性 seat_r,请尝试以下代码。

seats = {
seat_r:{
    index: vehicle.getBoneIndexByName('seat_r');
    positions: Vector3Mp;
}

>

CHIRAG
2021-07-29