Typescript Made Easy: Simplifying the Shift

thevatsal

Vatsal Awadhiya

Posted on June 26, 2023

Typescript Made Easy: Simplifying the Shift

Typescript is pretty hard to learn, especially if a developer's first language is Javascript. Often I get asked about Typescript, its type and syntax don't make much sense. Well, let's debug this together.

Why not use Javascript?

In present times, projects who focus on high-velocity shipping would prefer Javascript as their primary language because of its very nature.

  • Easy Development

  • Huge developer community and support

  • A gentle learning curve for anyone to start

  • Good developer tooling ecosystem to work with

But Javascript comes with its fair share of disadvantages as well. It quickly escalates development hindrances with a growing codebase and team size.

  • Type safety goes to the bin

  • No autocomplete :(

  • Unexpected undefined / NaN

  • Error handling becomes harder

For such reasons, developers started to find a language that provides the sophistication of languages like Go or Rust, but at the same time not sacrificing the benefits of Javascript.

Typescript joins the chat ...

As you can expect, Typescript was the solution developers came up with. It checked all the boxes.

  • Big Developer Community

  • Package ecosystem equivalent to Javascript's

  • The learning curve is slightly steeper than Javascript but not too much

  • Type safety

  • Auto-completion

  • Enabling developers a better error handling

It seems perfect for a fast pace development environment.

Transitioning from Javascript

If your first ever language is Javascript or something like Python, which is not statically typed, we don't implement any of the sophisticated types like interfaces or structs or enums, and this might even be foreign to you.

Let's dive into the basics!

Typecasting

Typecasting refers to assigning a type to a variable, function, or object even. In typescript, typecasting can be done using : symbol followed by a type, for example, string, number, boolean, etc.

Note: The same symbol is used to assign values of a property in an object as well.

// casting boolean type to
// isCool variable
const isCool: boolean = true;

// string variable
const name: string = "nezuko";

// literal type variable
let beingType: "demon" = "demon";

// you cannot assign anyother value
beingType = "human" // error

// number type variable
const age: number = 15;
Enter fullscreen mode Exit fullscreen mode

Types of Typescript

Let's learn about some commonly used types in Typescript:

Unions: Unions are a special data type that helps users to allocate multiple types of data, but apply only one at a time. The | operator can be thought of as an 'or' where it chooses between the types on either side.

const beingType: "human" | "demon" = "human";
// a creatureType can either be 'human' or 'demon'
Enter fullscreen mode Exit fullscreen mode

Interface: Interfaces can be thought of as blueprints for your classes or object. These provide abstracted structures for your objects. interface keyword is used to declare an interface.

interface IBeing {
    name: string;
    beingType: 'human' | 'demon';
    abilities: string[];
    age: number;
}
Enter fullscreen mode Exit fullscreen mode

Enums: These are user-defined sets of constants. These are majorly used in cases where there are only limited values are possible, like directions. The enum keyword is used to define an enum.

enum Direction {
    NORTH = 'North',
    EAST = 'East',
    WEST = 'West',
    SOUTH = 'South'
}

const direction: Direction = Direction.NORTH;
// value of direction is "North"
Enter fullscreen mode Exit fullscreen mode

Type: Well, since we are here, why stop at such limited types? You can use the type keyword to create your custom type using primitive or other user-defined types.

enum Todo {
    EAT = "Eat",
    SLEEP = "Sleep"
}

interface IBeing {
    name: string;
    beingType: 'human' | 'demon';
    age: number;
}

type Abilities = string[];

type Being = {
    todo: Todo,
    abilities: Abilities
} & IBeing;

const Nezuko: Being = {
    name: "nezuko",
    beingType: "demon",
    age: 13,
    todo: TODO.SLEEP,
    abilities: ["magic", "kick"]
}
Enter fullscreen mode Exit fullscreen mode

But, when it comes to application, types are not much different than interfaces, except interface has some additional features over types.

Special Symbols

In javascript, we use || for 'OR' operations, similarly, we can perform 'OR' operations on types using the | operator. Example:

const creatureType: "human" | "demon" = "human";
Enter fullscreen mode Exit fullscreen mode

Similarly, we use && for 'AND' operations, likewise in typescript, we can perform 'AND' operation on type using & operator. Example:

interface HumanProps {
    name: string;
    age: number;
}

interface DemonProps {
    ability: "strength" | "magic";
} 

const person: HumanProps & DemonProps = {
        name: "Nezuko",
        age: 14,
        ability: "magic"
};
Enter fullscreen mode Exit fullscreen mode

Typed arrays can be defined using [] symbol, followed by a type. For example:

const slayers: string[] = ["Tanjiro", "Muichiro", "Rengoku"];
// you can't add a number or an object to this array 
// as this is a string array
Enter fullscreen mode Exit fullscreen mode

Ethos of Typescript

Now that we are clear on the basics, let's dive into some of the practical aspects of development.

The good practices of Javascript development apply here as well, so I am going to talk more about good practices which involve types.

The following mentioned points are not some kind of rules by any means, but a set of good practices laid out by more experienced developers.

  • Typescript is very good at type inference, thus typecasting simple types like boolean, string, number, etc doesn't make sense. Only typecast when needed.

  • Don't use plurals to name your types.

  • Don't name your types in lowercase, prefer sentence-case(first letter capital). Types and variables should have a different casing. (This way your syntax highlighter isn't confused)

  • Prefix verbose generic types prefixed with T. For a generic type, using T is good enough for a single generic, but when you have multiple generics, prefer using more verbose names like TData. (Ignore this, if you are not familiar with Generic Types)

  • Prefixing your interface names with I . For example, IPerson, IOrganisation, etc. This one's a bit opinionated, and it might defer concerning the codebase or the developers you are working with.

Now there are some very controversial things as well, that you might love to watch people fighting over on Twitter.

  • type vs interface, what to use?

  • enums, worth using?

Resources

The best way to learn Typescript is to build projects using this language. And by using it, you will notice that Typescript is not much different than Javascript at the ground level. And when your project grows, you will see how it is different and why it helps.

But if you want to learn more about how types work, I would recommend the following exercises.

Some Youtube channels to follow for good explanations:

How to learn?

Well, I would not recommend making a leap of faith, as Typescript is not very fair for beginners a lot of times.

One shouldn't wait to acquire the whole knowledge of typescript before starting to write.

To start, just simply install the typescript dependencies in your projects and don't think too much about it, just write code as you would have with Javascript, but this time, write within .ts files.

Sometimes, getting familiar with something helps you more. With time, you would search for what you need and by searching-finding-solving, you learn. This is the best way of learning.

But there is a small bump on the road. tsconfig.json file is strictly required for the typescript to run, and configuring it is a real pain, so to make our life easier, we can just use this package tsconfig.json (yes, this is the name of the package) and run the following command to setup the a basic workable config.

npx tsconfig.json
Enter fullscreen mode Exit fullscreen mode

Conclusion

The concepts we learnt so far are just the surface of Typescript.

I am not trying to discourage you from learning Typescript, but this is something I missed starting myself; you should know what is the scope of Typescript. We have a lot to learn starting here.

Generic types, namespaces, modules, type manipulation, and much more. A huge sea of learning awaits those who dive in.

I hope I have made it easier for a beginner to jump-start their typescript journey.

But beware, there is no going back because after you learn typescript, you might never want to code in Javascript. 😅

Thanks a lot for reading!

💖 💪 🙅 🚩
thevatsal
Vatsal Awadhiya

Posted on June 26, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related