1

I like to convert a json string value to enum so it can show/render a custom string on the html page. error message: Type '{ id: number; name: string; status: string; }[]' is not assignable to type 'Status[]'

I have a json record like this:

{ id: 1, name: 'Some name', status: 'STATUS01' },

status.enum.ts

export enum Status {
  'STATUS01' = 'Operational',
  'STATUS02' = 'Some other status'
}

That enum is used in a model

import { Status } from './status.enum';

export class ServiceState {
  id: number;
  name: string;
  status: Status;
}

In the service there is a function to retrieve al statuses (dummy data):

getStatuses(): Observable<ServiceState[]> {
    const response = [
      { id: 1, name: 'One', status: 'STATUS01' },
      { id: 2, name: 'Two', status: 'STATUS01' },
      { id: 3, name: 'OneTwo', status: 'STATUS02' },}
    ];
    return of(response);
  }

the return is throwing the error

1
  • 1
    Please add the code which threw the error. Commented Jun 17, 2020 at 13:11

2 Answers 2

3

You should actually use the enum value:

export enum Status {
  STATUS01 = 'Operational',
  STATUS02 = 'Some other status'
}

const response = [
  { id: 1, name: 'One', status: Status.STATUS01 },
  { id: 2, name: 'Two', status: Status.STATUS01 },
  { id: 3, name: 'OneTwo', status: Status.STATUS02 },
  // ...
];

If you want to map the values from the enum:

getStatuses(): Observable<ServiceState[]> {
  const response = [
    { id: 1, name: 'One', status: 'STATUS01' },
    { id: 2, name: 'Two', status: 'STATUS01' },
    { id: 3, name: 'OneTwo', status: 'STATUS02' },
  ];

  return of(response).pipe(
    map((states) => states.map((state) => ({
      ...state,
      status: Status[state.status]
    } as ServiceState)
  );
}
Sign up to request clarification or add additional context in comments.

4 Comments

the webapi will return a STATUS01 (string) not Status.STATUS01. This is some dummy data.
@Babulaas Then your typing is incorrect, or you have to map the value in your response
I had to map the values. I had a long day. thank you for the fix.
@Babulaas But it's not even 4pm in Holland :D, you should try to work less, otherwise your productivity will go down too much!
1

I still don't understand your question, but you might have to map the response from the API to match your class type.

Service

public getStatuses(): Observable<ServiceState[]> {
  return this.http.get('url').pipe(
    map(data => data.forEach(item => {
      item.status = Status[item.status];
    }))
  );
}

If you're using the class only to assert the type, then a simple interface would suffice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.