Convert JS to Typescript

I have a simple Javascript app that counts duplicate numbers inside of an array...

I am currently learning Typescript and I would like to turn this Javascript into a Typescript...

I have angular up and running on my machine, but it can get overwhelming when learning everything about Angular 2.0 and Typescript at the same time.

What would be the best way to convert this to a Typescript?

$(document).ready(function() {
  var n = prompt("Enter your numbers").split(",");
  console.log(n);

  var counts = {};
  n.forEach(function(x) {
    counts[x] = (counts[x] || 0) + 1;
  });

  document.write(
    "<h1>Enter numbers when prompted!</h1>" +
      "<p>You entered following numbers:</p>" +
      n +
      "<br/>" +
      "<p>The occurence is as follows:</p>" +
      JSON.stringify(counts)
  );
});

Answers:

Answer

You really don't have to do anything, your JS would work fine in TS as well. But if you want to take advantage of all features this is how it would look:

$(document).ready(() => {

    var n = prompt("Enter your numbers").split(",");
    console.log(n);

    var counts : { [nr: string]: number } = {};
    n.forEach((x) => { 
        counts[x] = (counts[x] || 0) +1; 
    });

    document.write(`
    <h1>Enter numbers when prompted!</h1>
    <p>You entered following numbers:</p>${n}<br/>
    <p>The occurence is as follows:</p>${JSON.stringify(counts)}`);

});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.