报这个:Type of 'await' operand must either be a valid promise or must not contain a callabel 'then' member
我自己写了个class,里面有个then函数,是想模拟Promise,在不await时可以获得class的属性,await时,可以获得then方法异步返回的内容
// test.js
class Abc {
then (fn) {
setTimeout(fn, 3000)
}}
async function start () {
console.log('开始')
await new Abc()
console.log('结束')
}
start().finally(() => {
process.exit(0)
})
以上js是可行的,但是改成ts就不行了:
class Abc {
then (fn?: any) {
setTimeout(fn, 3000)
}
}
async function start () {
console.log('开始')
await new Abc()
console.log('结束')
}
start().finally(() => {
process.exit(0)
})
问题1:
setTimeout
的第一个参数不能为undefined
。修改方式,把
?
去掉。问题2:
PromiseLike
的then
函数签名不对:修改方式,
() => void
我建议你把所有的能够自动类型推导出来的那些类型,自己补全一下就明白了: