Search code examples
angulartypescriptdecorator

i am tryin to create a method decorator in angular but this error shows up


export class IceCreamComponent {
  @Emoji()
  flavor = 'vanilla';
}


// Property Decorator
function Emoji() {
  return function(target: Object, key: string | symbol) {

    let val = target[key];

    const getter = () =>  {
        return val;
    };
    const setter = (next:any) => {
        console.log('updating flavor...');
        val = `🍦 ${next} 🍦`;
    };

    Object.defineProperty(target, key, {
      get: getter,
      set: setter,
      enumerable: true,
      configurable: true,
    });

  };
}

i got error:

error TS7053: Element implicitly has an 'any' type because expression of type 'string | symbol' can't be used to index type 'Object'. No index signature with a parameter of type 'string' was found on type 'Object'.

11 let val = target[key];


Solution

  • The reason for the error is that string can't be used to index the type of Object because the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}. You can tell Angular what type of Object that you are expecting by giving its type like this

    let val = (key: string) => (target: Record<string, any>) => target[key];
    

    Now the error should disappear as we are telling the compiler that target will be a collection of string/value i.e. in our case (string/any) pairs.