Today I Learned: TypeScript Basics

“Two books on a desk near a MacBook with lines of code on its screen” by Émile Perron on Unsplash

Today (actually, it was at some point last week, but I’m just getting around to writing this up now) I learned TypeScript basics — basically, I learned a few key features it adds to standard javascript. This post will be a quick summary of the different features that I’ve learned about:

Types (duh)

One of the main advantages of TypeScript is that it allows explicit and implicit typing of variables which lends itself to less error-prone code. For example, you can explicitly or implicitly set the type of variables when you’re declaring them:

let bestNumber: number;
let bestString = 'Life, the universe, and everything';

In the above code block, TypeScript will assign a type to both variables. In the first line, a type is explicitly being defined to bestNumber. In the second line, TypeScript infers the type string for bestString because it’s being declared and initialized with a string value in one statement.

If bestString was declared in one statement and initialized in another, TypeScript would assign it the type “any” in the declaration statement. So, the below code would throw no errors when transpiled:

let bestString;
bestString = 'Life, the universe, and everything';
bestString = 42;

User-defined classes can also be used as types in TypeScript.

Classes

Classes are a new javascript feature as of ES6 but they’re also a feature of TypeScript where they can be transpiled down to an earlier version of javascript.

TypeScript classes add the ability to use the private keyword when creating variables. This means that the property is only accessible within a particular instance of the class.

There’s also the static keyword which allows methods defined with the keyword to be used without having to create an instance of the class.

Here’s an example of these three class features. The bolded words relate to the features just discussed:

class User {
name: string;
email: string;
private birthday: Date;
  constructor(name: string) {
this.name = name || '';
}
  static numberOfProperties(): number {
return 3;
}
}
const firstUser = new User('Zaphod Beeblebrox');
console.log(User.numberOfProperties());

Interfaces

Interfaces provide the ability to create custom types without having to define a full-on class. As an extension of the type concept, interfaces create a contract with other classes and objects that when initialized, the object must have certain properties.

Here’s an example of an interface:

interface User {
name: string;
email: string;
birthday?: Date;
}

The code block above illustrates a user interface where name and email must be defined when User is implemented, but birthday is optional.

One thing to note, since interfaces are an extension of the type concept in TypeScript, they do not get transpiled down to basic javascript.

Well, that’s it for today! Thanks for reading! 😄