DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

1

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:

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay