How to learn TypeScript effectively?
Tags: javascript, typescript, react, vscode
Published: 2020-02-28 15:17:54

---
title: How to learn TypeScript effectively?
published: true
date: 2020-02-28 15:17:00 UTC
tags: javascript, typescript, react, vscode
canonical_url: https://blog.atrera.com/javascript/2020/02/28/how-to-learn-typescript-effectively.html
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/mpmeebpdwjv5n3a4bt2k.jpg
---

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](https://dev-to-uploads.s3.amazonaws.com/i/38mcenkjukjpkpl80gpb.jpg)

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](https://blog.atrera.com/assets/typescript-demo-02.jpg)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/r1r8p6u9mpsr8np73tps.jpg)

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](https://github.com/DefinitelyTyped/DefinitelyTyped) repo. For example, if you want to find how React defined `<a>`, you can search in [DefinitelyTyped/types/react/index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L1881) and it is located in `React.AnchorHTMLAttributes`

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

```typescript
interface Link extends React.AnchorHTMLAttributes<HTMLElement> {
  ...yourProps
}
```

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

```jsx
<Link href="<YOUR-LINK>">My first link</Link>
```

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](https://www.typescriptlang.org/docs/handbook/basic-types.html) 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

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

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:

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

type Link = {
  href: string;
};

type ButtonWithLink = Button & Link;
```

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:

```typescript
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;
//     ...
//   }
//   ...
// }
// }
```

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.

```typescript
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"
```

### Partial

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

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

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

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.

```typescript
type Partial<T> = {
  [P in keyof T]?: T[P];
};
// all fields are optional in Partial
```

> If you want to know more, you can view [the official documentation](https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types-and-index-signatures).

## 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

- [TypeScript Documentation](https://www.typescriptlang.org/docs/home.html)
- [Introduction - TypeScript Deep Dive](https://basarat.gitbook.io/typescript/)
- [Conditional types in TypeScript](https://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/)