0

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)
  );
});
4
  • 1
    Any javascript file is also valid typescript. So you're sort of already done Commented Sep 4, 2017 at 19:45
  • If you're having trouble learning angular and typescript at the same time (and it's totally reasonable that you would) then don't. Work through some typescript tutorials. Get used to thinking in types. Then learn angular. Commented Sep 4, 2017 at 19:46
  • Yeah, I am following typescript course on pluralsight and it's great, however if a newbie has a question it can be tough to find an answer by just googling (typescript is not as widespread as Javascript) Commented Sep 5, 2017 at 10:34
  • Does this answer your question? Is there a tool to convert JavaScript files to TypeScript Commented Oct 2, 2020 at 11:33

1 Answer 1

1

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)}`);

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.