Is it possible to define the return type of a Promise?

Asked

Viewed 204 times

2

Good morning. I wonder if it is possible to define the return type of a Promise with typescript. I need this because I have a function that returns a precedent for a query in the database and I need that when the query is performed the return is an object (in my case a product), but then() returns a Unknown type. An example of the code that returns to Promise is attached:

getProtudo(idProduto) {
    return new Promise((res, rej) => {
      this.bancoSrc.banco.find({
        selector: {type: 'produto', _id: idProduto},
        fields: ['_id', 'descricao', 'referencia']
       }).then((result) => {
        this.produto = JSON.parse(result);
        res(this.produto);
       }).catch(err => {
        rej(err);
       });
    });
  }

And here’s the code that uses that code:

this.pickerCtrl.create(opts).then((picker) => {
  picker.present();
  picker.onDidDismiss().then(async (data) => {
    const col = await picker.getColumn('quantidade');
    this.produtoSrc.getProtudo(idProduto).then((prod) => {
      const qtd = col.options[col.selectedIndex].value;
      const pedido: Produto = new Produto(prod._id, prod.descricao, qtd, 10);
      this.listaPedido.add(pedido);
    });
  });
});
  }

I cannot create the object because when having to use the Prod. _id no create of my object, gives the following error: ": "Property '_id' does not exist on type 'Unknown'.

That way I posted up this working. But now I have another doubt, my object is coming as Undefined when I try to access its properties. Function:

getProtudo(idProduto) {
    return new Promise<Produto> ((res, rej) => {
      this.bancoSrc.banco.find({
        selector: {type: 'produto', _id: idProduto},
        fields: ['_id', 'descricao', 'referencia']
       }).then((result) => {
        res(result);
       }).catch(err => {
        rej(err);
       });
    });
  }

If I display it behind the console it displays the following response:

docs: Array(1)
0: {_id: "produto-1", descricao: "LANTERNA DIANT DIR", referencia: "KADETTE"}
length: 1
__proto__: Array(0)
__proto__: Object

Can anyone help me with that? Thanks in advance.

  • 1

    Gustavomgu, your method getProtudo is returning an array, so you are not able to access the property _id directly. Since its function should only return one object, instead of doing res(result), do res(result[0]). Maybe you need to do the JSON.parse also as you were doing in the first example.

  • You’re right, it was an array, to be able to access it I used result.Docs[0]. (I had to do this because I’m retrieving the information from a Nosql database)

1 answer

2


You just need to make use of generics to define the return of promise. In the case of a precedent that solves a number, the type of its return would be Promise<number>.

As you are returning an object, you can set the properties of your solved object in the signature of the function itself:

getProtudo(idProduto): Promise<{_id: string, descricao: string, referencia: string}> {

}

Or if you already have the type of this object defined, you can use some Typescript features to generate the type dynamically from a base interface:

// exemplo de interface
interface MeuTipo {
    _id: string
    descricao: string
    referencia: string
    outraInformacao: number
    maisInformacao: string[]
}

// Apenas as propriedades que foram buscadas no banco de dados
getProtudo(idProduto): Promise<Pick<MeuTipo, '_id' | 'descricao' | 'referencia'>> {

}
  • Thank you very much for the help. It worked well, but I still had a problem here. I’m not using an interface but a class, hence it displays an error message: 'Pick' only refers to a type, but is being used as a value here

  • Using class or interface should make no difference to the Pick, maybe if you post the definition of your class I can check what’s going on.

  • Please edit your question. Interpreting untrained comments is difficult. And include your class statement Produto also.

  • I edited the question and removed the comments with unformatted code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.