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 str string | 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.

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

class A {

    @boo()
    private str: string| null = null;

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

}

let a: A = new A();

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

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

class A {

    @boo("Other info")
    private str: 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:

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

class A {

    @boo
    private str: 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"