Typescript: Get the type of the custom interface with 'this'?

Viewed 77

If I return a 'custom' type of an interface and I use typeof then I get the orginal type (I understand why, I read it), but I can get the custom type?

If I have the following:

interface X{
   A:()=>Omit<typeof this, "A">,
   B:()=>Omit<typeof this, "B">,
   C:()=>Omit<typeof this, "C">,
}

let X : X = {...}

If want to make the following possible:

I.e. 1: X.A().B().C()

I.e. 2: X.C().A().B()

But not: X.A().B().A() (which currently is possible)

1 Answers

Typescript does have a polymorphic this type, so you can write this interface:

interface X{
   A:()=>Omit<this, "A">,
   B:()=>Omit<this, "B">,
   C:()=>Omit<this, "C">,
}

However this will not do what you want, as the this type is bound when the interface is created not based on the type of the object the function was called on.

We can capture the type of the object the function is invoked on using the this parameter of a function and a generic type parameter. This will work as you expect it to:

interface X{
   A:<T>(this: T)=>Omit<T, "A">,
   B:<T>(this: T)=>Omit<T, "B">,
   C:<T>(this: T)=>Omit<T, "C">,
}

let X: X = null!

X.A().B().C()
X.C().A().B()
X.A().B().A() // err

Playground Link

Related