Skip to content Skip to sidebar Skip to footer

Decorated Field Gives Read Only Error In Typescript

I am learning how to work with decorators and have the following problem. This is my code: function boo(): any { return function(target: object, propertyKey: string, descriptor

Solution 1:

With strict null checks null is not assignable to string. You need to make the type of strstring | null.

The other issue is that you need to invoke boo. boo is technically a decorator factory. The decorator itself is the function with the signature (target: object, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor.

functionboo(): any {
    returnfunction(target: object, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log("boo");
        return descriptor;
    }
}

classA {

    @boo()
    privatestr: string| null = null;

    constructor() {
        this.str = "test";
    }

}

leta: A = newA();

You need to use a decorator factory if you need to pass in extra parameters to the decorator. Ex:

functionboo(otherInfo: string): any {
    returnfunction (target: object, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log("boo " + otherInfo);
        return descriptor;
    }
}

classA {

    @boo("Other info")
    privatestr: string | null = null;

    constructor() {
        this.str = "test";
    }

}

In this case you don't really need to use a decorator factory, this would work as well:

functionboo(target: object, propertyKey: string) {
    console.log("boo");
}

classA {

    @booprivatestr: string | null = null;

    constructor() {
        this.str = "test";
    }

}

Although the above works, I would generally still use a decorator factory, easier to add parameters later and makes things consistent.

Post a Comment for "Decorated Field Gives Read Only Error In Typescript"