最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get number from promise? - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Nov 24, 2019 at 10:52 Cem Kaan asked Nov 24, 2019 at 10:23 Cem KaanCem Kaan 2,2363 gold badges32 silver badges62 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

Annotate the functions return type

function turnIntoNumber(get) : Promise<number> {
  return new Promise((resolve, reject) => {
    let shouldbeNumber : number =  Number(get);
    resolve(shouldbeNumber);
  });
}

You can annotate the type of resolve:

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

The return type of async function will always be wrapped in promise .So whether its JS or TS you cant return something which is not wrapped in promise.You can try something like below

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

makeMagic().then(data => {
    console.log(data);
})

StackBlitz Link

发布评论

评论列表(0)

  1. 暂无评论