aweiu
aweiu

Reputation: 392

How to change the method of chained calls at runtime?

LiveDemo

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>

class Chain<T = number> {
    fun1() {
      return this as Omit<this, 'fun1'>
    }

    fun2(arg: T) {
      return this as Omit<this, 'fun2'>
    }

    fun3() { 
      return this as unknown as Chain<string>
    }
}

// case1
new Chain()
    .fun1()
    .fun1() // it's ok

// case2
new Chain()
    .fun3()
    .fun2('')
    .fun1()
    .fun2(1) // it'ok

// case3
new Chain()
    .fun1()
    .fun2(1)
    .fun1() // expect a compiler error

As can be seen from the above code, typescript can "remember" a change in generics for a chain call, but "can't remember" the changes to the method.

So, how to make case3 also ok?

Upvotes: 1

Views: 84

Answers (1)

hasparus
hasparus

Reputation: 1324

@aweiu Lots of things become possible if you accept how hideous they look :D I've used explicit this parameter, made it generic and constrained to Partial<Chain<T>>.

Here's TS playground

Upvotes: 1

Related Questions