loading...
Cover image for Types and syntax in Typescript - beginner friendly explanation

Types and syntax in Typescript - beginner friendly explanation

ari_o profile image Arika O ・2 min read

The type system of a programming language includes all types of values that are supported by that language. It checks if the values we provide are valid and this happens before they are used by the program. Using its own type system, Typescript ensures the code will behave as we expect and it does that by performing type checks at compile time.

Before we lean how to write Typescript, we must understand the data types the language works with. Depending on who's explaining, they're roughly split in three categories and those are:

  • the any data type: is the super type of all types in TypeScript. In a sense, when using it it's like using no type at all, but I will explain this in the future.
  • built-in types: number, string, boolean, void, null and undefined
  • user defined types: interfaces, enums, classes, arrays and tuples etc.

Don't worry if many of the these words make no sense. We'll get to that in the future.

So how do we add all these types in our code? Using type declarations. We can add type declarations to variables, function parameters and function return types. The type is written after a colon following the variable name, like this: let randomWord: string = "example". The compiler will then check the types (where possible) during compilation and report type errors if there are any.

Some type examples would look like this (this is not a complete list of all the existing types in TS):

let whatever: any = "GOT"; // we're not sure of the type

let aNumber: number = 45; // type number

let aSting: string = "Paris"; // type string

let isLate: boolean = true; // type boolean

let hobbies: string[] = ["reading", "jogging", "sleeping"]; //  type array of strings

const addNumbers = (number1: number, number2: number): number => {
return number1 +number2;
} // a function that takes two arguments of type number and returns a number

const uselessFunction = (): void => {
alert("I'm a function that returns nothing!");
} // a function that returns void/ nothing
Enter fullscreen mode Exit fullscreen mode

If we would try to use any other type instead of the mentioned ones, the editor would complain. You can see this in action in the example bellow.

Alt Text

I suppose you are already starting to see the advantages of using Typescript over plain Javascript. In my next article I will write about numbers and strings in more detail.

Photo source: Stefan Gall/ @stefangall on Unsplash

Discussion

pic
Editor guide