1

In Angular2 I receive data from the server as a JSON object. One of the fields is a resource type. Which can be an image, video or audio. The enum looks like:

export enum MediaType {
  image,
  video,
  audio
}

However when I try to cast the response to an MediaType enum:

this.type = MediaType[data["type"]];

I got an error:

error TS2322: Type 'string' is not assignable to type 'MediaType'.

Any thoughts?

2 Answers 2

3

Is data['type'] part of the JSON response, containing a MediaType? If so it can be cast like this:

this.type = <MediaType> data["type"];
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for. Thanks!
1

Your data["type"] should be number, either 0, 1 or 2...

Consider this:

enum MediaType {
 image,
 video,
 audio
}
let type: MediaType;
type = MediaType[0] // image
type = MediaType[1] // video
type = MediaType[2] // audio

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.