Tutorial

3 Useful TypeScript Tips for Angular

Draft updated on Invalid Date
author

Jecelyn Yeen

3 Useful TypeScript Tips for Angular

This tutorial is out of date and no longer maintained.

Introduction

These are the 3 tips I found pretty handy while working with TypeScript:

  1. Eliminating the need to import interfaces
  2. Making all interface properties optional
  3. Stop throwing me an error, I know what I’m doing

Though I discovered these while working with Angular applications, all tips are not Angular-specific, it’s just TypeScript.

Eliminating the need to import interfaces

I like interfaces. However, I don’t like to import them every time. Although Visual Studio Code has an auto-import feature, I don’t like my source files been “polluted” by multiple lines of imports - just for the purpose of strong typing.

This is how we do it normally.

// api.model.ts
export interface Customer {
  id: number;
  name: string;
}

export interface User {
  id: number;
  isActive: boolean;
}
// using the interfaces
import { Customer, User } from './api.model'; // this line will grow longer if there's more interfaces used

export class MyComponent {
  cust: Customer;
}

Solution 1: Using namespace

By using namespace, we can eliminate the need to import interfaces files.

// api.model.ts
namespace ApiModel {
  export interface Customer {
    id: number;
    name: string;
  }

  export interface User {
    id: number;
    isActive: boolean;
  }
}
// using the interfaces
export class MyComponent {
  cust: ApiModel.Customer;
}

Nice right? Using namespace also helps you to better organize and group the interfaces. Please note that you can split the namespace across many files.

Let’s say you have another file called api.v2.model.ts. You add in new interfaces, but you want to use the same namespace.

// api.v2.model.ts
namespace ApiModel {
  export interface Order {
    id: number;
    total: number;
  }
}

You can definitely do so. To use the newly created interface, just use them as the previous example.

// using the interfaces with same namespaces but different files
export class MyComponent {
  cust: ApiModel.Customer;
  order: ApiModel.Order;
}

Here is the detail documentation on TypeScript namespacing.

Solution 2: Using d file

The other way to eliminate import is to create a TypeScript file end with .d.ts. “d” stands for declaration file in TypeScript (more explanation here).

// api.model.d.ts
// you don't need to export the interface in d file
interface Customer {
  id: number;
  name: string;
}

Use it as normal without the need to import it.

// using the interfaces of d file
export class MyComponent {
  cust: Customer;
}

I recommend solution 1 over solution 2 because:

  • d file usually use for external, 3rd party declaration
  • namespace allows us to better organize the files

Making all interface properties optional

It’s quite common where you will use the same interface for CRUD. Let’s say you have a customer interface, during creation, all fields are mandatory, but during an update, all fields are optional. Do you need to create two interfaces to handle this scenario?

Here is the interface

// api.model.ts
export interface Customer {
  id: number;
  name: string;
  age: number;
}

Solution: Use Partial

Partial is a type to make properties an object optional. The declaration is included in the default d file lib.es5.d.ts.

// lib.es5.d.ts
type Partial<T> = {
    [P in keyof T]?: T[P];
};

How can we use that? Look at the code below:

// using the interface but make all fields optional
import { Customer } from './api.model';

export class MyComponent {
  cust: Partial<Customer>;  /

  ngOninit() {
    this.cust = { name: 'jane' }; // no error throw because all fields are optional
  }
}

If you don’t find Partial declaration, you may create a d file yourself (e.g. util.d.ts) and copy the code above into it.

For more advanced type usage of TypeScript, you can read here.

Stop throwing me an error, I know what I’m doing

As a JavaScript-turned-TypeScript developer, one might find TypeScript error is annoying sometimes. In some scenarios, you just want to tell TypeScript, “Hey, I know what I am doing, please leave me alone.”.

Solution: Use @ts-ignore comment

From TypeScript version 2.6 onwards, you can do so by using comment @ts-ignore to suppress errors.

For example, TypeScript will throw error “Unreachable code detected” in this following code:

if (false) {
  console.log('x');
}

You can suppress that by using comment @ts-ignore

if (false) {
  // @ts-ignore
  console.log('x');
}

Find out more details here: TypeScript 2.6 release

Of course, I will suggest you always try to fix the error before ignoring it!

Conclusion

TypeScript is good for your (code) health. It has pretty decent documentation. I like the fact that they have comprehensive What's new documentation for every release. It’s an open source project in GitHub if you would like to contribute. The longer I work with TypeScript, the more I love it and appreciate it.

That’s it, happy coding!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Jecelyn Yeen

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more