Auto Cast with TypeScript?

1

Straight to the point:

Is there a way to perform auto cast using an interface as a template in Ionic (TypeScript + Angular 5)?

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

Scenario:

I'm using Ionic (Angular version 5) and a backend in PHP. My problem is when handling the data coming from the server using an interface that 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 application, everything works perfectly and I get the alerts when I try to use types that are not in the contract. The problem is when the 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, since the column is_correct is of type tinyint(1) , this data arrives at me as "0" or "1".

I did not want to have to do the cast manually, because I think a lot of gambiarra. Can anyone think of any way to perform an "automagic" conversion?

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

    
asked by anonymous 01.03.2018 / 22:50

2 answers

1

You can use:

result.data.is_correct == "1"

var x = "1";
console.log(x == "1");
x = "0";
console.log(x == "1");
    
01.03.2018 / 22:57
0

You can create one more property on your interface as well

is_correct:number;
is_correct_bool: boolean;

Then you can use

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

In this example the "QuestionInterface" would be your 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.

    
06.09.2018 / 13:20