Recommand · June 10, 2021 0

Can I get the property's value as number in a template property decorator in TypeScript?

I’d like to get the property’s value as number in such decorator. Could it be possible to do this without using any as target’s type?

function deco () {
  return function <T, K extends keyof T> (target:T, key:K) {
    /* Error:
Conversion of type 'T[K]' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type 'T[keyof T]' is not comparable to type 'number'.
    Type 'T[string] | T[number] | T[symbol]' is not comparable to type 'number'.
      Type 'T[symbol]' is not comparable to type 'number'.ts(2352)
    */
    if (typeof target[key] === 'number') {
      const value = target[key] as number
    }
  }
}

class A {
  @deco()
  static bar:number = 10
}