1

Can someone explain me why this code give me error?

var promise = new Promise((resolve, reject) => {
    resolve([1, 2, 3, 4, 5]);
});

async function doSomethingAsync() {
    var data = await promise;
    data.forEach(v => console.log(v));
}

doSomethingAsync();

When i try to compile this like tsc file.ts --target ES6 i have this:

error:async.ts(7,10): error TS2339: Property 'forEach' does not exist on type '{}'.

3
  • 1
    What happens if you change new Promise(...) to new Promise<number[]>(...)? Perhaps the type checker simply cannot infer a sufficiently specific type for promise? Commented Aug 7, 2016 at 17:03
  • By the way, aren't async and await es7 features? Commented Aug 7, 2016 at 20:47
  • They are, but AFAIK they are not actually stable and it will be changed in future (im not sure). Commented Aug 7, 2016 at 21:24

1 Answer 1

1

Actually i found solution , We can just simply add a generic type into our Promise like:

'use strict';

var promise = new Promise<any[]>((resolve, reject) => {
    resolve(["gdfgdfgdf", "dfggfd", 1, 2, {}]);
});

async function doSomethingAsync() {
    let data = await promise;

    for (let i of data) {
        console.log(i);
    }
}

doSomethingAsync();

Now it works perfectly without any mess in code :)

Sign up to request clarification or add additional context in comments.

1 Comment

I see, so the type checker just needed to know that your promise would be resolved with an array. Nice find!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.