How to use Promise.all() with Typescript

前端 未结 6 2053
旧时难觅i
旧时难觅i 2020-12-08 18:27

Here is what I want to do:

Promise.all([aurelia.start(), entityManagerProvider.initialize()])
    .then((results:Array) => {
        let aureli         


        
6条回答
  •  余生分开走
    2020-12-08 18:58

    If you'd like to keep type-safety, it's possible to extend the native type-definition of the Promise object (of type PromiseConstructor) with additional overload signatures for when Promise.all is called with a finite number of not-necessarily inter-assignable values:

    interface PromiseConstructor
    {
        all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>;
        all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>;
        ...
    }
    

    Add as many overloads as you need. This approach provides full type-safety for all elements in the value argument of the onfulfilled callback:

    Promise.all([1, "string", true]).then(value =>
    {
        let a: number = value[0]; // OK
        let b: number = value[1]; // Type 'string' is not assignable to type 'number'.
        ...
    });
    

提交回复
热议问题