【问题标题】:Typescript Error: Type '{}' is not assignable to type 'number'打字稿错误:类型“{}”不可分配给类型“数字”
【发布时间】:2017-09-07 03:51:57
【问题描述】:

我已经参考了其他答案,但无法解决我的问题

console.log(`home.ts : ${result} : ${typeof result},${typeof this.points}`);

返回

home.ts : 50 : number,number

但是这一行

 this.points = result;

抛出以下错误:

Typescript 错误:类型“{}”不可分配给类型“数字”。

功能齐全

getdefaultscore(){
  this.authService.getdefaultscore().then(
    (result)=>{
      console.log(`home.ts : ${result} : ${typeof result},${typeof this.points}`);
      this.points = result;
    },
    (err)=>{
      this.authService.alertnointernetconnection();
    }
  )
}

this.points 被定义为数字。

getdefaultscore() 的定义

  getdefaultscore(){
    return new Promise((resolve, reject)=>{
        let headers = new Headers();
        headers.append('Content-Type','application/json');
        this.http.post('mysite.com/ionuserpoint.php',JSON.stringify({defaultpoints:true}),headers)
        .subscribe(
            (res) =>{
                let data = res.json();
                data = parseFloat(data);
                alert(`defaults points : ${data}`);
                resolve(data);
            },
            (err) =>{
              reject(err);
            }
        );
    });
  }

我在 mysite.com 之前删除了http://www,因为 stackoverflow 会引发一些错误。

【问题讨论】:

  • 那么getdefaultscore()的定义是什么?
  • 如何声明this.points? points: number ?
  • 您是否使用积分:数字;或点=数字
  • @Fetra R 是的兄弟
  • @vSugumar 我在运行时看到了结果。但是this.authService.getdefaultscore() 的返回类型的定义是什么?一定是Promise<OfSomething>我相信

标签: angular typescript ionic-framework


【解决方案1】:

问题在于getdefaultscore,它返回Promise<{}>,理想情况下您应该将其更改为返回Promise<number>。由于您没有提供getdefaultscore 的代码,因此很难说您应该在那里进行哪些更改。要解决调用方的问题,您可以手动输入结果:

declare function getdefaultscore(): Promise<{}>; // Dummy declaration 
var points : number;
function x() {
  getdefaultscore().then((result: number)=>{
    points = result;
  },
  (err)=>{
  })
}

您可以在 Typescript 中考虑的另一个版本是使用 async/await 来简化您的 Promise 代码:

async function x2() {
  try {
    points = <number>await getdefaultscore()
  } catch (ex) {

  }
}

编辑:您在原始答案之后添加了getdefaultscore。由于您手动创建了 Promis,您只需将其输入到 Promise&lt;number&gt;

【讨论】:

  • 我试过 parseFloat(resolve) 但它抛出了一个不同的错误
  • 编辑了答案,你只需要输入promise to number
  • 这是假设返回的json只是一个数字,但这是另一个问题,如果数据是一个更复杂的对象pareseFloat会以其他方式失败
猜你喜欢
  • 1970-01-01
  • 2018-02-02
  • 2021-06-17
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
相关资源
最近更新 更多