Check out this code snippet from the playground.
class Smth {
public self(): this {
return this
}
public add() {
return this as this & { func(): Smth }
}
}
function f(x: Smth) {
const y = x.add() // Smth & { func(): Smth; }
y.func() // Ok
const z = y.self() // Smth & { func(): Smth; }
z.func() // Ok
}
function g<S extends Smth>(x: S) {
const y = x.add() // S & { func(): Smth; }
y.func() // Ok
const z = y.self() // S
z.func() // Error: Property 'func' does not exist on type 'S'.
}
The functions f
and g
exhibit different behavior where g
is generic:
function f(x: Smth) {
function g<S extends Smth>(x: S) {
However, a discrepancy arises at the line
const z = y.self()
In a non-generic function, self
correctly returns this
, but in a generic function z
ends up being just S
instead of S & { func(): Smth; }
.
How can I ensure that after calling y.self()
in the generic function, the correct type S & { func(): Smth; }
is returned?