Beginner’s TypeScript #5

Nhan Nguyen
1 min readDec 22, 2023

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;
}

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

const defaultUser = {}

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

getUserId(defaultUser)

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 = {}

👉 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:

--

--