Jobsdev
Jobsdev

Reputation: 1039

My interface not working - Variable boolean receives string

Typescript does not generate an error when I assign a string value to a boolean variable.

I forced an error to see how the typescript behaved and it did not generate the error that I expected.

I created a class with an attribute of type boolean. Then I created an interface. And I created the constructor method to initialize the variable.So I get a json where the variable is of type string. To my surprise the boolean variable receives the string. I wish it would generate an error. My code does not respect the type of the variable.

export class Product{

    public status:boolean;

    constructor(obj?: IProduct) { 

        if(obj)
        {
            this.status = obj.status;
        }
    }

}

interface IProduct {
    status:boolean;
}

my json of server

{status: "test"}

The test value is assigned to the status variable. And this should not be allowed.

Does anyone know how I can ensure that the variable only receives boolean value?

Upvotes: 0

Views: 1371

Answers (4)

Andreas
Andreas

Reputation: 21881

There's no type enforcement at runtime.

Decorators (an experimental feature) may solve your problem:

class Product {
    @validate
    public status: boolean;

    constructor(obj?: IProduct) { 
        if(obj) {
            this.status = obj.status;
        }
    }
}

interface IProduct {
    status: string;
}

function validate(target: any, propertyKey: string) : any {
    if (propertyKey === "status") {
        return {
            set: function (value: any) {
                if (typeof value !== "boolean") {
                    throw new Error("The supplied value is not of type boolean");
                }
            }
        }
    }
}

Upvotes: 4

Hasan Beheshti
Hasan Beheshti

Reputation: 3615

you can use this if statement in your constructor:

if (typeof obj !== 'boolean') {
    throw Error('type of obj must be boolean');
}

Upvotes: 0

Nuke Goldstein
Nuke Goldstein

Reputation: 104

Try:

interface IProduct {
    status: Boolean;
}

notice the interface typo and change nome to status.

Upvotes: 1

Rahul Singh
Rahul Singh

Reputation: 19622

It might have to do with you Interface

interface IProduto { // typo it should be IProduct
    nome:boolean; // and this should be name i suppose but i left it nome
}

And If you want to ensure that all values must have specified types you can set noImplicitAny to true in tsconfig.json,implies to TS Classes.

Upvotes: 1

Related Questions