【问题标题】:Return type `this` is spoiled when argument is generic当参数是泛型时,返回类型 `this` 被破坏
【发布时间】: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'.
}

函数fg唯一的区别是第二个是泛型的:

function f(x: Smth) {
function g<S extends Smth>(x: S) {

但由于某种原因,他们开始在生产线上表现不同

const z = y.self()

方法self 被声明为返回this,它在非泛型函数中工作正常(z 变为Smth &amp; { func(): Smth; })。但是由于某种原因,在泛型函数中z 只得到S 而不是S &amp; { func(): Smth; }

在泛型函数中调用y.self() 后,我应该写什么来获得正确的类型S &amp; { func(): Smth; }

【问题讨论】:

  • @JackWilsdon,不,this 表示与this 具有相同的类型,但不保证相同的实例。无论如何,我已经展示了 2 个函数,在第一个函数中它按预期工作(至少对我来说)。有什么原因导致这些函数对this返回的含义有不同的期望?

标签: typescript generics


【解决方案1】:

你可以做到,但不能使用多态this。如果您将self 设为通用并在呼叫站点推断出this,则它可以工作。

class Smth {
    public self(): this {
    //public self<T>(this:T): T {
        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'.
}

Playground Link

不确定为什么多态 this 在这种情况下不起作用。我相信您可能想在 GitHub 上提出问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2023-02-16
    • 2020-10-26
    • 1970-01-01
    • 2019-08-19
    相关资源
    最近更新 更多