Folks, this one simple trick will improve your refactoring whenever you need to use an undefined value in TypeScript.
Here, I've got a createUser function where I'm creating a bunch of different users. But, I've now got a new requirement here, which is I also need to add a role to some users and some not.
interface UserInfo {
name: string
}
export const createUser = (userInfo: UserInfo) => {}
So here, what I could do is I could say for some users, I'm gonna pass them the admin role like this.
interface UserInfo {
name: string
role?: "admin"
}
except I really need to go through every bit of my code base. Imagine these are all spread out over different files, and I need to check who I need to make an admin and who I don't.
createuser({
name: "Matt",
})
createUser({
name: "David",
})
createUser({
name: "Laura",
})
createUser({
name: "Andarist",
})
createUser({
name: "Farzad",
})
createUser({
name: "Jenny",
})
So, I know that for instance that I need to make Matt an admin, I need to make David an admin, but Laura is not an admin. So the way that I like to do this is I like to add an in-between step here, which I can either pass role or undefined like this.
interface UserInfo {
name: string
role?: "admin" | undefined
}
And this adds a different behavior here. It's saying we need to pass the property role or we can pass undefined there. So even though technically this is undefined here, we still need to add role as undefined.
createUser({
name: "Laura",
role: undefined,
})
And that means that I do get all of the inference and the auto completes that I'm looking for. And it means that I can just go back later and just remove all of these undefined roles.
So that's really useful. And it's sometimes even desirable to keep this type signature if you do want to allow passing of undefined, but you want to make it really visible to the user that they've done that.
So again, this is a really nice little syntax switch that you can do moving from either "you don't need to pass this property" or "you do need to pass this property, but you can still pass undefined".
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.