ts不支持await含then方法的class吗?

报这个: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)
})
阅读 4.1k
2 个回答

问题1: setTimeout 的第一个参数不能为 undefined

type TimerHandler = string | Function;

setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;

修改方式,把 ? 去掉。

问题2: PromiseLikethen 函数签名不对:

interface PromiseLike<T> {
    /**
     * Attaches callbacks for the resolution and/or rejection of the Promise.
     * @param onfulfilled The callback to execute when the Promise is resolved.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of which ever callback is executed.
     */
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
}

修改方式,() => void

我建议你把所有的能够自动类型推导出来的那些类型,自己补全一下就明白了:

class Abc {
  then (fn: () => void): void {
    setTimeout(fn, 3000)
  }
}

async function start () : Promise<void> {
  console.log('开始')
  await new Abc()
  console.log('结束')
}

start().finally(() => {
  console.log(1243)
})
  then (fn: ()=>void) {
    setTimeout(fn, 3000)
  }

then 的参数不能是 any 。

issue on typescript

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题