问一个关于 ts 的问题
 发布于 7 年前  作者 lyf103104  3329 次预览  最后一次回复是 7 年前  来自 问答 

WechatIMG22.png

WechatIMG23.png


  1. get 函数要求返回一个 promise 对象,而 return this.name,并不满足,为何编译通过?

  2. 直接 return 一个字符串,编译器报错,为什么 return this.name,却可以通过编译?(this.name 实际也是一个字符串)

4 回复
yviscool

this.name 是个 any , 因为 this 运行时确定,你也可以手动指定 this

function get(this:string): Promise<string> {
    this.name =  'zjl';
    return this.name;
  } 
lyf103104

@yviscool

this.name 的类型是 any 可是 get 函数要求返回 promise 对象,这样也可以满足吗?

JsonSong89

@lyf103104 any全都能过,当然前提是你tsconfig里面允许.

我估计你是想这样写吧


async function get(this: string): Promise<string> {
    return ""
}