简体   繁体   中英

Assigning a nested interface in typescript

I am trying to assign a value to a nested interface in typescript but the compiler seems to throw an error even though the format matches correctly


type wheelT = [contemp: number, motemp: number, error: string];

interface getData {
  frontLeft: wheelT[];
  frontRight: wheelT[];
  rearLeft: wheelT[];
  rearRight: wheelT[];
  voltage: number;
  amps: number;
  mode: string;
  FWD: string;
}

initjson: getData = {
    frontLeft: [0, 0, "000"],
    frontRight: [0, 0, "000"],
    rearLeft: [0, 0, "000"],
    rearRight: [0, 0, "000"],
    voltage: 0,
    amps: 0,
    mode: "--",
    FWD: "--",
  };

essentially throws an error at frontLeft, frontRight, rearLeft, rearRight saying it is not assignable.

Your type does not match correctly. Your wheelT type is a tuple with 3 entries. frontLeft (as well as frontRight, rearLeft, rearRight) is of type wheelT[] - so an array of tuples. Change this to wheelT (without the array brackets) and it should work.

Without the array brackets, getData looks like this:

interface getData {
  frontLeft: wheelT
  frontRight: wheelT;
  rearLeft: wheelT;
  rearRight: wheelT;
  voltage: number;
  amps: number;
  mode: string;
  FWD: string;
}

Here the working TS Playground .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM