Beginner's TypeScript #5
Nhan Nguyen
Posted on December 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 = {}
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
👉 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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Posted on December 22, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.