Reputation: 2240
So I have a class that defines a value as a boolean:
export class MySettings {
myProperty: boolean;
}
Then in my component:
import { MySettings } from "./settings";
@Component(){
selector: "my-thing",
template: require("./my-thing.html")
}
export class MyThing {
settings: MySettings = new MySettings;
@Input()
set myProperty ( setting: boolean ){
this.settings.myProperty = setting;
}
}
if I pass something in that is not a boolean like so:
<my-thing myProperty="banana"></my-thing>
I get no error of any kind. It simply sets the resulting string that is passed to the settings object. Which shouldn't be possible? What am I missing here?
Upvotes: 0
Views: 1084
Reputation: 3575
TypeScript transpiles down to JavaScript and while you have types in TypeScript, it will only give you an error at compile time. And since it can't read the property of the object you are setting from HTML, you get no error. And since the transpiled JavaScript is not type specific, you get no error there either. If you want to enforce only valid values, do it in your setter:
set myProperty ( setting: boolean ){
if (settings.toString().toLower().include('true,false') {
this.settings.myProperty = setting;
}
}
Upvotes: 2
Reputation: 8335
This is expected behavior, the Type assertion that TypeScript
brings to the table is compile time only and limited only to .TS files and will not be applied to the templates or at runtime.
You would need to guard the input property by checking it's type and only accepting it if it meets your desired type at runtime.
Upvotes: 1