2017-09-06 69 views
1

我刚才提到其他的答案,但没能解决我的问题打字稿错误:类型“{}”是不能分配给输入“号”

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

回报

home.ts : 50 : number,number 

,但此行

this.points = result; 

会抛出以下错误:

Typescript Error: Type '{}' is not assignable to type 'number'.

全功能

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因为计算器抛出一些错误。

+2

getdefaultscore()的定义是什么? –

+0

你如何声明this.points? '分:数字'? – Fetrarij

+0

是否使用points:number;或points =数 – amyogiji

回答

1

问题在于getdefaultscore,它返回Promise<{}>理想情况下,您应该将其更改为返回Promise<number>。由于您没有提供getdefaultscore的代码,因此很难说您应该在那里做出什么改变。为了解决对发送方的问题,您可以手动键入结果:

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

另一个版本,你可以在打字稿考虑使用异步/等待简化您Promise代码:

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

    } 
} 

编辑:您原始答案后添加getdefaultscore。由于您手动创建promis,因此只需将其键入Promise<number>即可。

+0

我试过parseFloat(解析),但它抛出了一个不同的错误 –

+0

编辑答案,你只需要键入承诺编号 –

+0

这是假设返回的json只是一个单一的数字,但这是一个不同的问题,如果数据是一个更复杂的对象'pareseFloat'将在其他方法 –

相关问题