700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > ts 报错:‘new‘ expression whose target lacks a construct signature implicitly has an ‘any‘ type.

ts 报错:‘new‘ expression whose target lacks a construct signature implicitly has an ‘any‘ type.

时间:2023-10-10 00:49:55

相关推荐

ts 报错:‘new‘ expression  whose target lacks a construct signature  implicitly has an ‘any‘ type.

文章来自公众号:前端学海

TS 项目报错

报错内容

'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.

即将要实例化的函数中没有 construct,并且隐式类型为 any

报错原因

很多基于 ES5 的构造函数的写法在 TS 的检查下不支持,目前还会有很多较老的库没有更新为 TS 项目,并且已经非常稳定没有维护更新的计划。

解决方式

显示的将构造函数的类型定义为 any,兼容 ES5 写法中没有 construct 的问题

const RedisStore = new (Redis as any)({host: RedisConfig.host,port: RedisConfig.port})

建议

后续 TS 是主流方向,如果你有写方法库的打算,或是在项目中使用类的话,最好都是以 ES6 写法为基础,减少可能出现的写法及类型问题

示例放最后

ES5写法

function Component () {this.count = 1}Component.prototype.add = function () {this.count++}// 实例化const demo = new Component()console.log(demo.count)demo.add()console.log(demo.count)

ES6 写法

class Component {constructor(){this.count = 1}add () {this.count++}}// 实例化const demo = new Component()console.log(demo.count);demo.add()console.log(demo.count);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。