INTRODUCTION
I am currently working with Angular 6.
In Angular, typescript is utilized to allow you to specify the data type of your function's arguments:
public fun1(aaa: number) {
console.log(aaa);
}
If I attempt to call fun1
with a parameter of a different type, an error will be thrown:
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 effectively when I have control over the arguments in my code files.
However, there are situations where fun1
may be called with parameters retrieved from a backend source.
Since Typescript does not perform runtime checking, no errors would be shown and the code within fun1
would execute with the unexpected input like [1, 2, 3]
.
-- edited --
The issue isn't just limited to backend responses. In some cases, a library might alter the data type without your knowledge. For example, when using Reactive Forms with a control that should contain a number, it could inadvertently convert the value to a string during editing.
QUESTION
Is there a standard method for implementing type checking at runtime?
I've considered something along these lines:
public fun1(aaa: number) {
if (typeof aaa !== 'number') {
console.warn('wrong type');
} else {
console.log(aaa);
}
}
, but WebStorm alerts me that
typeof check is always false: 'aaa' always has type 'number'
.
Including such checks at the beginning of every function seems cumbersome and unnecessary. Does anyone have a more efficient solution for this dilemma?