【发布时间】:2020-12-06 01:50:49
【问题描述】:
这里是代码: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'.
}
函数f和g唯一的区别是第二个是泛型的:
function f(x: Smth) {
function g<S extends Smth>(x: S) {
但由于某种原因,他们开始在生产线上表现不同
const z = y.self()
方法self 被声明为返回this,它在非泛型函数中工作正常(z 变为Smth & { func(): Smth; })。但是由于某种原因,在泛型函数中z 只得到S 而不是S & { func(): Smth; }。
在泛型函数中调用y.self() 后,我应该写什么来获得正确的类型S & { func(): Smth; }?
【问题讨论】:
-
@JackWilsdon,不,
this表示与this具有相同的类型,但不保证相同的实例。无论如何,我已经展示了 2 个函数,在第一个函数中它按预期工作(至少对我来说)。有什么原因导致这些函数对this返回的含义有不同的期望?
标签: typescript generics