DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Beginner's TypeScript #5

Image description

Assigning Types to Variables

We have an interface that represents a user within our system:

interface User {
  id: number;
  firstName: string;
  lastName: string;
  isAdmin: boolean;
}

Enter fullscreen mode Exit fullscreen mode

A function called getUserId takes in a user, and returns its id.

const defaultUser = {}

const getUserId = (user: User) => {
  return user.id;
}

getUserId(defaultUser)
Enter fullscreen mode Exit fullscreen mode

We have an error because it calls getUserId and passes in a defaultUser that does not match the User contract.

We will check the TypeScript docs and determine how to change defaultUser.

👉 Solution:

By adding : User to defaultUser, we tell TypeScript that we want it to conform to our User interface.

const defaultUser: User = {}
Enter fullscreen mode Exit fullscreen mode

Now TypeScript will display errors at the line where defaultUser is declared.

We also benefit from autocompletion for the properties!

The same : Type syntax can be used with other types, including numbers and functions:

let a: number = 1
Enter fullscreen mode Exit fullscreen mode

👉 Summary:

As we write TypeScript, we need to think about where we want our contracts to be, and what needs to be done to meet them.


I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (0)