INTRODUCTION
I'm using Angular 6.
Angular uses typescript, so you can type your function's arguments:
public fun1(aaa: number) {
console.log(aaa);
}
If I'll try to call fun1 with parameter of other type - I'll get an error:
public fun2() {
this.fun1([1, 2, 3]); // TS2345: Argument of type 'number[]' is not assignable to parameter of type 'number'
}
THE PROBLEM
Type checking works well if I can control the arguments in my files.
But maybe fun1 is called with some parameters which I get from backend.
Typescript doesn't workin in runtime, so it won't show any errors, the code of fun1 would just run with [1, 2, 3].
-- edited --
Backend response is not the only source of problem. Sometimes a library can change type of your data and you might not know about it. An example would be using Reactive Forms with a control which should be a number - it's converted to string when you edit the number.
QUESTION
Is there some common way to handle type checking in runtime?
I thought about something like:
public fun1(aaa: number) {
if (typeof aaa !== 'number') {
console.warn('wrong type');
} else {
console.log(aaa);
}
}
, but WebStorm then tells me typeof check is always false: 'aaa' always has type 'number'.
Also putting something like this at the top of every function seems like adding a lot of unnecessary code.
Does someone have a good solution for this?
HttpClientin Angular allows you to hint the shape of the API response you're expecting. If you really wanted you could also validate it at that boundary, so you don't spread runtime type checking throughout the whole app.