【问题标题】:Get type of construct function in Typescript interface在 Typescript 接口中获取构造函数的类型
【发布时间】:2019-08-29 05:42:30
【问题描述】:

给定一个 Typescript 接口:

interface Foo {
    bar(a: string): Bar
}

我可以通过索引接口类型来获取函数的类型:

type X = Foo["bar"] // X is (a: string) => Bar

但这不适用于构造签名:

interface Foo {
    new(a: string): Bar
}

type X = Foo["new"] // Property 'new' does not exist on type 'Foo'

有没有办法访问这种类型(实际上只是返回类型,Bar)?我拼凑了这个,但我确信有更好的方法:

const foo: Foo
const inst = new foo('')
type X = typeof inst // Bar

【问题讨论】:

    标签: typescript constructor


    【解决方案1】:

    Typescript 在 2.8 版本中为此案例添加了一个名为 InstanceType 的类型。

    interface Foo {
        new(a: string): Bar
    }
    
    type X = InstanceType<Foo>; // Bar
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      • 2017-09-17
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多