2

I have a model class p

class P {
    constructor(public ids: number[]) {
        console.log(ids);
    }
}

On calling service api I got response like :

var response: any = { ids: "this is string" }

Now when we create an instance of model P using 'response'

let p1 = new P(response.ids);

this should produce error : ids type mismatch

but there is no error.

Now question is How to reject response, if it doesn't match given model type?

  • If you want to be type safe, you could generate the response models based on their API specifications (eg. there are tons of swagger generation scripts/tools) this you can be sure when coding you dont get the wrong type – Joel Harkes Dec 07 '17 at 15:53

2 Answers2

4

TypeScript compiles to JavaScript. During runtime, so when you are calling the service API, the types or typehinting are unknown. These are all only relevant during the compilation step.

You should manually check if the api is responding with the correct types using either typeof, or instanceof if you are checking for an object. In case if ids is an array of numbers, you can do this:

isArrayOfNumbers(array: any): boolean {
  return Array.isArray(array) && array.every(value => typeof value === 'number');
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • I am working on an angular4 project and my services return like below. return >this.http.get(${this.endPoint.mock).‌​map(_card => { return new Card(_card.purchaseId, _card.productName); }); so, Is this ok or I should have to do explicit type check. – DurGesh kuMar RAO Dec 07 '17 at 10:46
0

Typescript gets compiled to javascript so there are no types on runtime. If you want to display that message you have to check this explicitly. Something like Test for array of string type in TypeScript

jbojcic
  • 954
  • 1
  • 11
  • 25