代码之家  ›  专栏  ›  技术社区  ›  Christian Vincenzo Traina

在TypeScript中定义数组类型

  •  3
  • Christian Vincenzo Traina  · 技术社区  · 6 年前

    我正在为一个项目使用TypeScript,我需要使用 Promise.all(...)

    Promise.all(
      firstRequest,
      secondRequest,
      ...,
      nthRequest
    )
    .then((array : [FirstType, SecondType, ..., NthType]) => {
      // do things with response
    });
    

    现在,既然 [FirstType, SecondType, ..., NthType]

    所以我试着:

    export interface ResponseParams {
      [0]: FirstType;
      [1]: SecondType;
      ...
      [n]: NthType;
    }
    

    以及:

    .then((array : ResponseParams) => {
      // do things with response
    });
    

    类型“ResponseParams”不是数组类型。

    如何将类型外部化并使代码更干净?

    非常感谢。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    6 年前

    type ResponseParams = [FirstType, SecondType, ..., NthType]
    

    但我要指出的是 array 将在没有显式类型注释的情况下进行推断(至少10次):

    declare let firstRequest : Promise<{a: number}>
    declare let secondRequest : Promise<{b: number}>
    declare let nthRequest : Promise<{c: number}>
    Promise.all([
        firstRequest,
        secondRequest,
        nthRequest
    ])
    .then((array) => { // array is of type [{a: number;}, {b: number;}, {c: number;}]      
    // do things with response
    });
    
        2
  •  0
  •   k0pernikus    6 年前

    所有人都接受一个通用的 T ,这使您可以完全控制返回类型。因此,您可以为期望返回的每个承诺定义元组,同时仍保持类型。

    我将使用async/await语法这样做:

    interface Foo {
        gnarf: string;
    }
    
    interface Bar {
        poit: string;
    }
    
    const createFoo = async (): Promise<Foo> => {
        return {
            gnarf: "random",
        };
    };
    
    const createBar = async (): Promise<Bar> => {
        return {
            poit: "hurz",
        };
    };
    
    const doStuff = async () => {
        const [foo, bar] = await Promise.all<Foo, Bar>([createFoo(), createBar()]);
    
        return `${foo.gnarf} and ${bar.poit}`;
    };
    
    doStuff().then(console.log).catch(console.error);