Search code examples
typescripttypescript-decorator

Cannot access properties of parent class from a type parameter that extends the class


I have a decorator that adds some properties to a class and another decorator that needs that property added by the first one, like:

// this class adds the type support
abstract class TypeDefClass {
  readonly p!: number;
}

type Newable<T = any> = new (...args: any[]) => T;

const addProperties = <T extends Newable<TypeDefClass>>(target: T) => {
  return class extends target {
    p: number = 0;
  }
}

const readProperty = <T extends Newable<TypeDefClass>>(target: T) => {
  // use the target.p property
  target.p // property p does not exist on T, but it should right?
}

however if I do

// though this will not applicable to a class, since it's not newable
// and will result in a type mismatch
const readProperty = (target: TypedefClass) => {
  target.p; // its fine
}

I doubt my definition of type Newable is incorrect, and I don't know which definition of readProperty is correct. I am fairly new to decorators, any help is much appreciated.

Playground


Solution

  • Looks like it's because you didn't instantiate the class.

    When I pulled in your code I:

    1: Noticed you spelled TypedefClass wrong ;) It should be TypeDefClass as per your definition :) 2: Was able to access the p property after target was instantiated.

    If you want to access it statically, perhaps declare p to be static?