Automatic cast with Typescript?

Asked

Viewed 138 times

1

To the point:

There is a way to cast automatically using an interface as a model in Ionic (Typescript + Angular 5)?

If not, you can make Lint recognize that an object coming from the server is not within the expected interface agreement?

Setting:

I’m using Ionic (Angular version 5) and a PHP backend. My problem is when it comes to handling the data coming from the server using an interface I created.

I have two interfaces that work together:

export interface QuestionInterface {
    id_question: string,
    answers: Array<AnswerInterface>,
    question_text: string
}

export interface AnswerInterface {
    answer_text: string,
    is_correct: boolean
}

Inside the app, everything works perfectly and I get alerts when I try to use guys who aren’t in the contract. The problem is when data arrives from the server.

http.get('xxx')
.toPromise()
.then(result=> {

})

The request returns an object that contains, in result.data, data from a table. However, like the column is_correct is the type tinyint(1), this data comes to me as "0" or "1".

I didn’t want to have to cast it manually, because I think it’s very common. Can anyone think of any way to perform an "automatic conversion"?

Otherwise, how to make the object coming from the server go through a contract check with the interface?

2 answers

1


  • Two problems: I’ll have to scan all the objects and I didn’t want to have to; the types are string, not number and this test will always be true. I understand that I can do this casting manually, but I wanted to avoid, if there was a way to perform this cast.

  • Ah, yes. It solves the second problem but, still, I need to sweep all the elements. If you can avoid...

  • 1

    I guess that’s where you want magic.

0

You can create an extra property on your interface like this

is_correct:number;
is_correct_bool: boolean;

Then you can use the

this.QuestionInterface.answers.forEach(element => {
        element.is_correct_bool = element.is_correct == "1" : true ? false;
});

In this example the "Questioninterface" would be its variable of this type ... after receiving the return in JSON.

So it was going to be done at once without having to manually pass 1 to 1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.