Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number from promise?

Why does typescript says?

let shouldbeNumber: number Type 'unknown' is not assignable to type 'number'.Vetur(2322)

turnIntoNumberwill always get strings of numbers such as 1,2,3,4,5,6... , so I know shouldbeNumber will always be a number. How can I convince typescript or develop this piece of code? :-)

async function makeMagic() {
  let shouldbeNumber: number = await turnIntoNumber("2");
}
function turnIntoNumber(get) {
  return new Promise((resolve, reject) => {
    let shouldbeNumber : number =  Number(get);
    resolve(shouldbeNumber);
  });
}

Would you please help me to turn this javascript into a better typescript? Thanks in advance.

like image 477
Cem Kaan Avatar asked Jan 01 '23 11:01

Cem Kaan


1 Answers

Annotate the functions return type

function turnIntoNumber(get) : Promise<number> {
  return new Promise((resolve, reject) => {
    let shouldbeNumber : number =  Number(get);
    resolve(shouldbeNumber);
  });
}
like image 178
PaulB Avatar answered Jan 13 '23 14:01

PaulB