What is Typescript anyway?
Tags: typescript, javascript, node
Published: 2023-05-05 09:36:42

Let's have a look at what Typescript is under the hood, how it is similar to and also how it differs from JavaScript, we'll also look at some of the features of Typescript. Things we will consider in this post includes;

- What Typescript is.
- Features of Typescript

### What you need to know

You need to have a good understanding of what JavaScript is and how it works to understand this post. let's dive in

visit [Netcreed](https://thenetcreed.com) to read more articles like [this](https://blog.thenetcreed.com/post/sQ9JclhFRpH0SJmlNw1z)

Typescript is a superset of JavaScript that compiles to JavaScript. Typescript adds optional static typing on top of JavaScript. Typescript was published by Microsoft in October of 2012. 

We all know the headaches that comes with using JavaScript, Typescript is a solution to the drawbacks that comes with using JavaScript for application development. Typescript was created to address the issues that JavaScript had with large scale application development. Typescript can be used for both client side scripting that is frontend development and server side scripting. Typescript ships with it's own default compiler or you can use the babel compiler to transpile Typescript code to JavaScript. The default TypeScript compiler itself is written in TypeScript and compiled to JavaScript 

Our favorite Code editor VS Code is built with Typescript and provides out of the box next level support for Typescript. This why you get awesome support when developing applications with Typescript in VS Code. Typescript is an implementation of ECMAScript and as such valid JavaScript code is also valid Typescript code because Typescript is a strict superset of ECMAScript 2015. ECMAScript 2015 itself is  a Superset of ECMAScript 5 which is what we call JavaScript, Typescript just adds a set of syntactical language extensions based on the proposal,  the extension that Typescript adds to JavaScript is as follows;

- Type annotations and compile-time type checking
- Type inference
- Type erasure
- Interfaces
- Enumerated types
- Generics
- Namespaces
- Tuples

Let's talk about some of the features that Typescript adds to JavaScript.

## Type annotation and compile-time type checking

Typescript allows developers to declare a type for a variable by annotating the variable with a type. The syntax is described in the code example below

```typescript
let variable: type = value
```
Type annotation allows for compile-time type checking where the value assigned to each variable is checked before the Typescript code is compiled to JavaScript to ensure that it matches the type specified for that variable when it was declared. There are types that can be used for annotation that matches all of the primitive data types supported by JavaScript like `string`, `boolean`, `number`. A variable may be annotated with one type or a union of two or more types.

```typescript
let variable: type | another_type = value
```

## Type Inference

If a variable is not annotated with a Type when it is declared, The Typescript compiler is smart enough to determine the type of the variable from the value assigned to it and thus infer it onto the variable. This allows Typescript code to be less verbose and bear a similarity to JavaScript. Most of the time the Typescript compiler will infer the type of a value to a variable and as such eliminate the need to explicitly annotate each variable with a type, although sometimes the Typescript compiler cannot infer a type to a variable then you should explicitly annotate the variable with the desired type.

## Type erasure

JavaScript is a weakly typed language and does not support type annotation, thus when Typescript code is compiled to JavaScript the Typescript compiler will remove all type annotation, the types in your code are thrown away and aren't used in the source code you generate.

```typescript
const name: string = "Sam"
```

Will eventually be transpiled into 

```javascript
const name = "Sam";
```

You should always have this in the back of your mind when building applications with Typescript.

## Interfaces

Typescript also extends JavaScript by adding interfaces, an interface is just a contract that specifies how an object/class will look like and behave. In order words an interface will describe the properties and methods that can be defined on a class or an object. TypeScript also creates implicit interfaces when you define an object with properties and don't specify an interface for it. Implicit interfaces are derived from an Object by the compiler when we do not explicitly specify an interface for that Object. Interfaces are defined using the interface keyword.

Interfaces are capable of describing the wide range of shapes that Typescript objects can take, ranging from optional properties to return type for methods of an object, interfaces are very powerful constructs in TypeScript. They can be implemented with a class or used for the type of an Object literal.

```typescript
interface UserInterface {
  name: string;
  age: number;
  sayHello: (name: string) => string
}
```

We can use this interface with a class as described below.

```typescript
class User implements UserInterface {
  name: string
  age: number

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  sayHello(name: string) {
    return `Hello ${name}`
  }
}
```

Or we can use it with an Object literal as described below.

```typescript
const User: UserInterface {
  name: "Sam",
  age: 28,
  sayHello: (name: string) => {
    return `Hello ${name}`
  }
}
```

## Enumerated types

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allows us to define a set of named constants. An enum can be defined using the `enum` keyword. Enums can be of two types

- Numeric Enums
- String Enums

### Numeric Enums

Numeric Enums store their values as numbers. Let's say we want to store a set of Platforms which our users use. An enum in TypeScript for this would be:

```typescript
enum Platform {
  Desktop,
  Web,
  Mobile,
}
```
The enum above contains three values: Desktop, Web and Mobile. Here, enum values start from zero and increment by 1 for each member. Numeric enums are always assigned numeric values when they are created. Each value in the enum would be represented as;

```typescript
Desktop = 0;
Web = 0;
Mobile = 0;
```
The first value always have a numeric value of 0, while the other values in the enum are incremented by 1. We can  initialize the first numeric value ourselves so we can rewrite the same enum as:

```typescript
enum Platform {
  Desktop = 1,
  Web,
  Mobile,
}

console.log(Platform.Desktop)
// 1
```

### String Enums

String enums are similar to numeric enums, however the enum values are initialized with string values as opposed to numeric values.

The benefits of using string enums is that they offer better readability. Consider the same Platform enum example, but represented as a string enum.

```typescript
enum Platform {
  Desktop = "DESKTOP",
  Web = "WEB",
  Mobile = "MOBILE",
}

console.log(Platform.Desktop)
// DESKTOP
```

## Generics

Generics are an important tool that can help developers create reusable components in TypeScript. Generics are a way to create functions and classes that can work with multiple types. This allows you to create code that can be used in many different contexts. By leveraging generics, you can create code that is both versatile and efficient. Generics ensures that a program is flexible as well as scalable in the long term.

Generics provide developers with a way to write code that is both dynamic and type-safe. This means that the code you write can be used with a variety of types and will still be type-safe. let's see an example of a generic function.

```typescript
function generic<T>(param: T): T {
 return param;
}

const gen = generic(2);
const newGen = generic("sam");
console.log(typeof gen);
console.log(typeof newGen);
// number
// string
```

When we make use of the Generics we allow typescript to infer the type of a function argument based on the value we pass in. We can narrow our generics to only handle a set number of type, this allows our code to be flexible only up to a given extent.

```typescript
function generic<T extends string | number>(arg: T): T{
    if (typeof arg == "string"){
        return arg.toUpperCase()
    } return Math.pow(arg, 2);
}

generic("sam");
generic(2);
generic({name: "foo"}) // not possible
```

## Namespaces

Code organization in TypeScript is done using namespaces. Namespaces are simply named JavaScript objects in the global namespace. Namespaces are very user-friendly architecture. They can span several files in contrast to modules. Visit the  [Namespace Documentation](https://www.typescriptlang.org/docs/handbook/namespaces.html) to learn more about Namespaces in TypeScript.

## Tuples

A tuple is a typed array with a pre-defined length and types for each item in the array. Tuples are great because they allow each element in the array to be a known type of value. To define a tuple, specify the type of each element in the array.

```typescript
let tupule:  [string, number, boolean];

tupule = ["Sam", 28, true];
```

Tuples are no different from arrays, just they have a fixed length and the item at each index is typed.

That's it for what Typescript is, leave your thoughts about Typescript down below in the comments section.