StephenRios StephenRios - 24 days ago 8
TypeScript Question

Passing a string to an input with a type of boolean does not yield an error

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?

Answer

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;
        }
    }
Comments