TypeScript for Python Developers

A quick introduction to TypeScript for experienced Python developers

--

If you already know Python, you might be interested in learning TypeScript. It is getting more and more popular. It works in your browser. And in many facets, it is a very similar language.

However, most places to learn a programming language are focused on new developers. Very few articles or tutorials cut down to the essentials of the new language while leaving out the basic of programming. This article will provide a brief but dense overview how TypeScript works, and how you can get started easily. It contains the basic syntax, loops, types, shorthands are more.

The basics

TypeScript is a superset of Javascript. So any Javascript code is valid TypeScript code but not the other way around. TypeScript compiles into JavaScript code, which can then be interpreted by the executor, a browser or NodeJS.

TypeScript can be used as a front end language, generally as part of a framework or library. Or as a backend with node.js, often as a webserver but in theory also as a pure backend.

Syntax

Like most other languages, TypeScript uses brackets to create scopes, versus Python’s indentation based style. CamelCase TypeScript is also the convention versus Python’s snake_case .

Basics

Here are a list of basics to get started, first as Python code and then TypeScript code. I’ll use Python’s typing to compare to TypeScripts typing. TypeScript’s typing is actually also optional, and can infer types very well.

Basic syntax

Equality

There are two equality operators in JavaScript and TypeScript. == checks for value equality. This will attempt to typecast the values to eachother. === will check for value equality and for type.

This casting makes JavaScript do strange things some of the time. A lot of the WtfJs items are about equality due casting of the items.

Assignments

First of all, assignment in TypeScript is done with a keyword. There are three key words: var, let and const. Learning this is quite easy: use const if the value is a constant and won’t change, use let is the value is going to change and don’t use var . The reason to not use var is about variable scoping, and is not covered here.

Because of this scoping and explicit assignment, you also need to define variables at the right time. For example, if you want to have a new variable be large in an if block, and small in the else block. Then you must make sure to define the variable before the if else block. If you don’t, the complier will complain because the variable does not exist outside of the if else block.

Loops and lists

TypeScript has two type of for loops. One more classic one, one more modern one. Next to that, the Array prototype (aka the list type), has a couple of nice built in functions, like forEach, map, filterMost (but not forEach) return a new array and don’t modify the old array. This is very nice for the functional, pure functional folks who attempt to not change any variables and just make new ones.

Types

These compare mypy types with TypeScript. The format is Python — TypeScript. A complete list of TypeScript types can be found here.

  • int, float, double, long number
  • str string
  • List[T]Array<T> or T[], with T being any other type
  • Dict Object
  • Tuple[str, int, dict][string, number, object]
  • TypedDictCustom interface

TypeScript and JavaScript only has one types for numbers without a specific reference to integers or floats. In some sense it makes sense, but makes casting to integers annoying.

While talking about types, someone cannot skip the two different empty values in TypeScript: null and undefined.

  • null denotes an non-existing object or the fact that there is no input. It can be compared to Python’s None.
  • undefined is returned when an attribute is referenced that does not exist. It is similar to Python’s KeyError or AttributeError.

TypeScript doesn’t error out if you reference an non-existing value on an object. However, referencing anything on undefined does throw a TypeError. Both are falsy, and undefined i snot equal to null.

A small difference in bool casting of types, is that an empty list and an empty object are truthy in TypeScript.

Objects

Objects in TypeScript are very similar to dictionaries in Python.

There are some differences though:

  • Each key also becomes an attribute. There is no real difference between someObject.key or someObject['key'], except that the TypeScript compiler might complain less with the second varation.
  • You cannot use variables in the creation, as keys are taken as strings in the assignment.
  • As metioned, referencing non-existing fields returns undefined.

Functions

Functions work much like in Python, with some small differences. Functions can have default values. However, function calls must be filled in left to right, and do not support keyword arguments. They do support a random number of arguments with spread parameters.

To make up for the fact that there are no kwargs, TypeScript implementations often provide an options/props/… last argument, which contains all of the keyword-only arguments. For example, AWS CDK TypeScript has a props argument, while the equivalent Python CDK provides individual keyword arguments.

Classes and interfaces

Classes are your run of the mill standard OOP classes, while interfaces provide a structure but no implementation.

Unlike Python, a class can only extend one other class. A class can implement multiple other classes or interfaces. An interface can only extend another interface, not implement one.

This also shows a nice shorthand in TypeScript. A constructor can define public name: type and the compiler will understand that it has to do this.name = name in the initialisation.

Exceptions

Exceptions behave much in the same way in TypeScript as they do in Python. Keyswords differ slightly but most things carry over. TypeScript however does not allow to catch multiple error types at the same time like Python does.

Shorthands

Some great things about modern JavaScript and TypeScript are the shorthands. They help speed your development up a lot, though they are a bit slower than pure implementations with loops etc.

The list includes the basic bool inference like in Python, or short circuiting with a default. But TypeScript has a lot more of these.

This article provides a more elaborate overview of shorthands, but the ones above covered the most important ones.

Ecosystem

Like Python’s pip, TypeScript (and JavaScript) have a package manager called Node Package Manager (npm). It installs all packages locally in a folder node_modules which is infamous for getting very large.

It’s also a common idea that there is really a package for the most trivial stuff in npm. Personally I have the feeling that pip packages are a bit higher quality and better maintained, but that’s just my opinion. There are probably less PyPi packages though.

The main important libraries are:

  • HTTP calls (like requests): axios, rxjs/ajax, request (deprecated)
  • Front ends: React vs Angular vs Vue and many, many more
  • Back ends: Node.js, express (routing)
  • Time and date: moment.js
  • Reactive data: RxJs.

A bit about RxJs as this is the coolest library I have worked with. It helps you deal with streaming data. It is integral in Angular, where almost all data are observables. It’s a nice way to start learning functional programming.

There is also an RxPy library, if you want to work like this in Python.

Conclusion

The good

  • The TypeScript compiler and typechecker feels much better than mypy. For VS Code it also seems to have better compatability
  • Null checking is super usefull, especially when working with user data.
  • The shorthands can safe a lot of time
  • It’s basically the only language accepted in a browser, and can also be used on a server. This allows for full JS/TS stacks
  • I had a lot of fun with RxJS, which forced me to think in a functional way
  • It’s a very flexible language (like Python), so you can always find a style that suits you
  • A lot of libraries and a huge community

The bad

  • Working with dates is really a pain in the ass, especially coming from datetime and dateutil
  • Running a script is slightly more annoying as you can’t just to python script.py
  • Some of the libraries are not as high quality as some in Python

The Ugly

  • It’s still JavaScript
  • npm_modules
  • Error handling is often very confusing, needing to go deep into your stack trace to find anything interesting
  • Compatability is annoying, as you don’t control the environment. Yes there are still people using IE7. Whether you want to bother making your site run on it, is your decision

The different

  • As mentioned, the style is different. It leans much more towards functional programming than OOP. It takes some getting used to
  • People actually install a library for any trivial function

There is obviously a lot I did not mention. But as experienced developers, you know that the answer is one Google search or StackExchange solution away.

Message me if you have any questions, or ask them in the comments. Thank you for reading my first technical Medium article!

--

--

Anton De Meester
Analytics Vidhya

Fulldstack developer in Stockholm. Always looking to learn and grow. Thinking a lot about a Total Wealth App.