PUBLISHED

04.02.2021

SHARE

TwitterFacebookLinkedin

Typescript can be confusing

At Codesphere, we code mostly in Typescript, not necessarily because it is our favorite language, but because we found out that it made us the most productive.

To start off, here are some benefits of Typescript that make us more efficient:

  • ability to code in the same language in both frontend and backend
  • (mostly) great OO + types
  • asynchronous code

However, recently I came across two very strange behaviors, (I know, they are common in the JavaScript Bubble) and I felt the urge to share them!

1: [‘1’, ‘2’, ‘10’].map(parseInt);

I came across this when I wanted to format some user input, convert it into numbers and put them in a chart.

Don’t believe me? Open up a console in your browser, paste in the following, and press enter.

[‘1’, ‘2’, ‘10’].map(parseInt);

This does not work, because map passes three arguments into parseInt() on each iteration. The second argument index is passed into parseInt as a radix parameter. So each string in the array is parsed using a different radix. ‘2’ is parsed as radix 1, which results in NaN, ‘10’ is parsed as radix 2, which is 3, and ‘1’ is parsed as the default radix 10 because its index 0 is falsy.

That being said, the following code will now work as intended:

[‘1’, ‘2’, ‘10’].map(numStr => parseInt(numStr));

2: Inheritance of ‘readonly’ in Typescript

During a code review at Codesphere, my colleague Roman came across the idea to make methods readonly. What happened next left us a little confused.

It’s actually not possible to make a method readonly, but it is possible to make a readonly property with a function type, which has the same effect.

Interestingly enough, it is not possible to assign the property again for instances of the same class, but it is possible to inherit a class and override the property, as well as, assign the property on an instance of a subclass.

class Roman {

    readonly jonas: () => void = () => console.log(“huh?”);

}

class Elias extends Roman {

    jonas: () => void = () => console.log(“oh no, override works!”);

}

const elias = new Elias();

elias.jonas(); // oh no, override works!

elias.jonas = () => console.log(“oh no, assignment works too!”);

elias.jonas(); // oh no, assignment works too!

That’s all for now, I hope that you enjoyed the read! The support for Typescript is one of the core features of Codesphere IDE. By the way — my name is Saji and I joined the Codesphere team because I love coding and our vision to improve the developer experience.

What is your experience with Typescript? Feel free to share your story about the things you find confusing in Typescript!

MORE

Early Access

Sign up to get
exclusive early access

Codesphere is a collaborative, interconnected programming environment that thrives software innovation.
Start new ideas just like that - production ready, with reusable containers (pods).