V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
px920906

求教, typescript 中函数返回一个 class 时类型如何定义?

  •  
  •   px920906 · Mar 10, 2020 · 2485 views
    This topic created in 2240 days ago, the information mentioned may be changed or developed.

    需求是这样的:

    有一个定义好的 class Foo,函数 bar 会调用一次 Foo 的一个静态方法,然后返回 Foo。

    那 bar 的返回类型应该怎么定义?

    google 一通找到 ts 架构师的PR,完全看不懂。。。

    现在的做法是从 so 复制粘贴来的:

    type Constructor<T extends {} = {}> = new (...args: any[]) => T
    

    但调用这个返回的类似乎只有Function的原型方法比如 toString,之前 Foo 的静态方法都没了:

    const _Foo = bar()
    _Foo.init(config) // 编译器提示 TS2339:属性 init 在 Constructor 上不存在
    

    怎样才能定义一个类型,保留这个类的静态方法?

    求教神通的 v 友!

    2 replies    2020-03-10 15:21:12 +08:00
    huanglexus
        1
    huanglexus  
       Mar 10, 2020
    很简单,typeof

    class Foo {
    static m1() {
    console.log('m1')
    }
    }

    function bar(): typeof Foo {
    Foo.m1()
    return Foo
    }
    px920906
        2
    px920906  
    OP
       Mar 10, 2020
    @huanglexus 可以了!谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3538 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 11:57 · PVG 19:57 · LAX 04:57 · JFK 07:57
    ♥ Do have faith in what you're doing.