Why does typescript says?
let shouldbeNumber: number Type 'unknown' is not assignable to type 'number'.Vetur(2322)
turnIntoNumber
will 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)
turnIntoNumber
will 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 03 Answers
Reset to default 5Annotate 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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743664287a4486711.html
评论列表(0条)