1

I am wanting to convert a JSON "string" that I pull from an api into my Typescript model, if i change one of the props from enum to string it works quite easily, however I cannot seem to map it to an enum despite hours of searching and trying different things.

I have a model that holds an array of types like this

export enum SEAT_TYPE {
  ECONOMY = "ECONOMY",
  PREMIUM_ECONOMY = "PREMIUM_ECONOMY",
  BUSINESS = "BUSINESS",
}

export type Seat = {
  number: string;
  type: SEAT_TYPE;
  status: boolean;
};

export class SeatingPlan {
  seating: Seat[] = [];
}

I then pull something like this from an api

  [{
    number: "1A",
    type: "BUSINESS",
    status: false,
  },
  {
    number: "1B",
    type: "BUSINESS",
    status: false,
  },
  {
    number: "1C",
    type: "BUSINESS",
    status: false,
  }]

An i'm using just a basic loop function to map over each element and convert it to a typed object like this

export function convert(json: Array<Seat>) {
  return json.map(
    (seat) =>
      <Seat>{
        number: seat.number,
        type: seat.type as keyof typeof SEAT_TYPE,
        status: seat.status,
      },
  );
}

But where i call my

convert(JSON)

I get this error and I'm totally lost at this point, i'm semi-new to typescript and i feel like i'm missing something quite simple, any help would be greatly appreciated.

Argument of type '{ number: string; type: string; status: boolean; }[]' is not assignable to parameter of type 'Seat[]'.
  Type '{ number: string; type: string; status: boolean; }' is not assignable to type 'Seat'.
    Types of property 'type' are incompatible.
      Type 'string' is not assignable to type 'SEAT_TYPE'.

Thanks in advance.

  • If the input to `convert()` is already a `Seat[]` then you have nothing to convert; it's already done. If the input is `{number: string; type: string; status: boolean}[]` and you don't want to do any runtime verification, then there's still nothing to convert at runtime, you just want to *assert* like `const seats = json as Seat[];`. Does anything go wrong if you do that instead? – jcalz Jun 29 '22 at 23:22
  • Does this answer your question? [How to parse JSON string in Typescript](https://stackoverflow.com/questions/38688822/how-to-parse-json-string-in-typescript) – doublethink13 Jun 30 '22 at 09:42

0 Answers0