In typescript can we type a variable with an object?

Asked

Viewed 511 times

0

In typescript can we type a variable with an object? Example: funcaoExemplo(obj: { [key: string]: any }) {}

  • 4

    Victor, if you have this object defined, why not create a class and type with the same?

  • Hi Daniel! Thanks for the help. How do you type an object with a class? Could you give me an example? Att.

1 answer

3


Victor,

Below is a very simple example of parameter typing and function return:

//Exemplo de classe
class MinhaClasse {
  key: string = "";
}

//Exemplo de função que recebe um parâmetro de tipo específico
function funcaoComParametroTipado(parametro: MinhaClasse) {
  console.log(parametro);
}

//Exempĺo de função que retorna um tipo específico
function funcaoComRetornoTipado(): MinhaClasse {
  let minhaClasse: MinhaClasse;

  minhaClasse = new MinhaClasse();
  minhaClasse.key = "Retorno";

  return minhaClasse;
}

let minhaClasse = new MinhaClasse();

minhaClasse.key = "Parâmetro";

//Chamada com parâmetro tipado
funcaoComParametroTipado(minhaClasse);

//Chamada com retorno tipado
console.log( funcaoComRetornoTipado() );

Here I create the Minhaclasse class that has a property called key, I use this class in parameter typing and also return typing.


The documentation of typescript is great, if you want to take a look, below the link:

https://www.typescriptlang.org/docs/home.html

  • 1

    Thanks for the help! Helped a lot!

Browser other questions tagged

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