I have a question with Angular 2 and typeScript
I have an interface like this:
export interface DataForm{
cuenta:string;
nombre:string;
}
Then I have a function like this:
public datas(x:DataForm){
console.log(x);
}
And I have a variable and I obj:number=20;
pass it as a parameter to the function I made:
this.datas(this.obj);
In the console it returns 20.
Not being the same type is not supposed to show an error. My question is how do I check that the parameter I receive is equal to the indicated type of the function.
That function would actually receive the fields of a form with those fields, but that question arose, how do I show an error if they are not the same type. In the editor if it marks the error but when compiling it does not show any error. I think that making a type of would be the solution, only I am left wondering why it does not throw an error when compiling.
The problem is that TypeScript has been designed as an extension of javascript, so that compilers can detect this type of errors, so it only helps you at compile time, that is, "when you are in the editor", because then everything is "transpiles" to JavaScript, and it will really work for you no matter what you pass to it (a priori). That's why it shows you 20 on console. In fact, the editor is the one who should give you some warning, indicating the type problem, in a linter plan.
To be sure, I'm not sure if just a would suffice
typeof
, as it might always return aObject
and not a concrete class (just like in JS). The safest thing in TS would be to use ainstanceof
, like so:They explain it better in the official documentation
The solution in vanilla JS is to use
Object.prototype.hasOwnProperty
. Something like what they say here