How to learn TypeScript effectively?

snowleo208

Yuki Cheung

Posted on February 28, 2020

How to learn TypeScript effectively?

TypeScript is notorious for its steep learning curve, especially to a programmer who doesn't have exposures or not familiar with Object-oriented Programming (OOP). Moreover, there are lots of exceptions to Javascript even you are familiar with OOP.

The question is: how can I learn TypeScript effectively?

How to know what type is it?

You may feel lost when first try to learn TypeScript. That's how I try to figure out what type it is.

Get help from your IDE

I am using Visual Code right now and it perfectly integrates with TypeScript. When you hover a variable in your script, you can see the types generated by TypeScript.

hover types

If not, you can hover it and right click -> to see type definition. Then VSCode should show you the file where the type definitions located.

see type definition
Alt Text

After typed, VSCode can have autocomplete on objects too! Amazing!

Your last resort: DefinitelyTyped

For some application like React, they have their own types in DefinitelyTyped repo. For example, if you want to find how React defined <a>, you can search in DefinitelyTyped/types/react/index.d.ts and it is located in React.AnchorHTMLAttributes

How can you use it? It is simple, you can try:

interface Link extends React.AnchorHTMLAttributes<HTMLElement> {
  ...yourProps
}
Enter fullscreen mode Exit fullscreen mode

Even you didn't define any props, you can still use your Link component in this way without getting TypeScript linting error:

<Link href="<YOUR-LINK>">My first link</Link>
Enter fullscreen mode Exit fullscreen mode

It is because you already extend the type definition from React, so you can use it without defining them yourself.

How to write your own type?

When you are learning TypeScript, the best way to improve your skills is to practice more. The TypeScript documentation should be a great starting point.

When trying to write your types, I think the following methods are extremely useful and productive for your workflow.

Union type

type Button = {
  variant: 'primary' | 'secondary';
};
Enter fullscreen mode Exit fullscreen mode

Union type helps you to further restrict the input, for example, in the above Button component, you can just write string for variant props. It means you can put in any string you like (that may or may not break your code). after implementing union type, you can only input primary or secondary.

If you try to input strings other than primary or secondary, TypeScript will block you!

Intersection Types

You can also combine different types into one:

type Button = {
  variant: 'primary' | 'secondary';
};

type Link = {
  href: string;
};

type ButtonWithLink = Button & Link;
Enter fullscreen mode Exit fullscreen mode

In the above example, ButtonWithLink has properties of both Button and Link type. That means you can use the same props e.g. variant or href in this new type.

typoeof

It is normal to have a huge object in a complex application, for example:

const jsonObj = {
  type: 'test',
  variant: 'test',
  value: 3,
  disabled: false
  purchase: {
    name: 'T-shirt';
    qty: 200
    type: {
      size: 'XL',
      color: 'white'
      ...
    }
    ...
  }
};

type JsonType = typeof jsonObj;

// Equals to
// type JsonType = {
//   type: string,
//   variant: string,
//   value: number,
//   disabled: boolean,
//   purchase: {
//   name: string;
//   type: {
//     size: string;
//     color: string;
//     ...
//   }
//   ...
// }
// }
Enter fullscreen mode Exit fullscreen mode

The above sample data is in a simple data structure, you can still do the typing manually. but when you encounter a JSON object with nested objects or array, the typeof function becomes super useful.

keyof

The same rationale applies to keyof, it gets all keys in the object.

const jsonObj = {
  type: 'test',
  variant: 'test',
  value: 3,
  disabled: false
  color: {
    red: '#f44336',
    purple: '#9c27b0',
    pink: '#e91e63'
  }
};

type Color = keyof typeof jsonObj.color;
// Equals to
// type Color = "red" | "purple" | "pink"
Enter fullscreen mode Exit fullscreen mode

Partial

Partial is useful when you just need one field in your type. For example:

type Person = {
  name: string;
  age: number;
  email: string;
};

const updateData = (userData: Partial<Person>) => {
  // so you can just update one field
};
Enter fullscreen mode Exit fullscreen mode

Be careful, Partial makes all the fields optional under the hood, just make sure you don't need a mandatory field when you use it.

type Partial<T> = {
  [P in keyof T]?: T[P];
};
// all fields are optional in Partial
Enter fullscreen mode Exit fullscreen mode

If you want to know more, you can view the official documentation.

My Journey

TypeScript looks scary at first.

I tried to learn TypeScript on my own by forcing myself to use Angular a year ago, which is using TypeScript. However, even after I finished my toy project in Angular, I think I only learn a little bit of TypeScript. Few months before, I started to use TypeScript in my company, when I see how the others wrote in TypeScript, suddenly I learn a lot of how to use keyof, typeof, Partial, Pick etc.

The main keys are to write a lot and always find the best way to do typing (i.e. find the best way to be lazy!).

I hope my learning journey of TypeScript would help you too!


Read more

💖 💪 🙅 🚩
snowleo208
Yuki Cheung

Posted on February 28, 2020

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

Sign up to receive the latest update from our blog.

Related

Make your JavaScript Typed Safe
javascript Make your JavaScript Typed Safe

January 10, 2022

Building a VSCode Extension: Part Four
javascript Building a VSCode Extension: Part Four

September 14, 2020

Building a VSCode Extension: Part Three
javascript Building a VSCode Extension: Part Three

September 1, 2020

How to learn TypeScript effectively?
javascript How to learn TypeScript effectively?

February 28, 2020