【typescript】interface里面用new表示什么类型

前言

  • 今天群里一个人问了个ts问题,说类型不正确,我一看,他的interface里面用了new,一般写ts很少有interface里写new的,interface里写new的一般都是在d.ts里写的。

答案

  • 我翻了ts文档,其中有句是这么说的:The function signature is prefixed with the keyword ‘new’ indicating that the ‘BankAccount’ function must be called as a constructor. It is possible for a function’s type to have both call and constructor signatures.
  • 就是说如果签名有前缀new表示这个函数必须要被构造器调用。
  • 简单说就是class里面那个constructor。
  • 所以一般人不会在interface里面用new,因为class本来就能代表类型,并且还能作为值使用,为什么不用class还非要写个同名的interface?
  • 文档意思简单用代码表示就是这么回事:
  class fakeNum{
    constructor(_val:string){}
    static aa='xx'
    static bb =11
  }
  interface fakeNum2{
    new(val:string):fakeNum
    aa:string
    bb:number
  }
  let kk:fakeNum2 = fakeNum
  • 这个kk就是fakeNum2的类型,也等于fakeNum的类型。所以没事谁又写个interface,只有写d.ts给别人用才会这么写。
  • 顺便好奇试了下能不能用es5的class写法,发现不行,提示普通函数new的类型不对。
发布了163 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/yehuozhili/article/details/104724160