#Get type of `this` class context

5 messages · Page 1 of 1 (latest)

broken parrot
#

Is there a way that I can get the actual class type of a this context inside of a class? Example below:

class TestClass {
   static prop = {
     testing: true
   }


   someFunc() {
     // type Explicit = typeof TestClass.prop -> { testing: true } works fine

     // But I want something like ->
     type TestType = this // -> this
     
     // I want something like:
     // type TestClassType = typeof this."class" -> TestClass
     // type TestClassProp = typeof TestClassType.prop -> { testing: true }
   }

Basically I want to be able to reference the type of the class for an instance. Is this possible?

stark pier
#

this is achievable through constructor in js, which is unfortunately not specifically typed in ts

exotic magnet
#

you can do this with declaration merging to provide types for this.constructor

late roverBOT
#
webstrand#8856

Preview:```ts
class TestClass {
static prop = {
testing: true,
}

someFunc() {
this.constructor.prop // okay now

// But I want something like ->
type TestType = typeof this.constructor

// I want something like:
type TestClassType = InstanceType<
  typeof this.constructor
>
type TestClassProp = typeof this.constructor.prop

}
}

interface TestClass {
constructor: typeof TestClass
}```

exotic magnet
#

note that this makes inheritance more difficult