Ensure that all call sites must be given value

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".

Transcript

0:00 Folks, this one simple trick will improve your refactoring whenever you need to use an undefined value in TypeScript. Here, I've got 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.

0:18 Here, what I could do is I could say for some users, I'm going to pass them a role, which is going to be admin like this role?: "admin". Except I really need to go through every bit of my code base. Imagine these are all spread out of different files. There's 40 of them. I need to check who I need to make an admin and who I don't.

0:36 Here, I know that for instance I need to make Matt an admin, I need to make David an admin. Laura is not an admin for instance. 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.

0:53 This adds a different behavior here. It's saying we need to pass the property role or we can pass undefined them. Even though technically this is undefined here, we still need to add role as undefined. That means that I do get all of the inference and the auto completes that I'm looking for.

1:14 It means that I can just go back later and just remove all of these role undefined like so. Bam. 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.

1:33 This again 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.

This one little tip has saved me hours of refactoring time. Passing string | undefined instead of ?: string ensures that ALL call sites must be given a value - amazing when you need to check every case in your repo.

Discuss on Twitter

More Tips

Play Type Predicates

Type Predicates

1 min

Play TypeScript 5.1 Beta is OUT!

TypeScript 5.1 Beta is OUT!

2 mins

Play How to Name your Types

How to Name your Types

4 mins

Play Don't use return types, unless...

Don't use return types, unless...

4 mins

Play TypeScript 5.0 Beta Deep Dive

TypeScript 5.0 Beta Deep Dive

6 mins

Play Conform a Derived Type Without Losing Its Literal Values

Conform a Derived Type Without Losing Its Literal Values

1 min

Play Avoid unexpected behavior of React’s useState

Avoid unexpected behavior of React’s useState

1 min

Play Understand assignability in TypeScript

Understand assignability in TypeScript

2 mins

Play Compare function overloads and generics

Compare function overloads and generics

1 min

Play Use infer in combination with string literals to manipulate keys of objects

Use infer in combination with string literals to manipulate keys of objects

1 min

Play Access deeper parts of objects and arrays

Access deeper parts of objects and arrays

1 min

Play Understand how TypeScript infers literal types

Understand how TypeScript infers literal types

1 min

Play Get a TypeScript package ready for release to NPM in under 2 minutes

Get a TypeScript package ready for release to NPM in under 2 minutes

1 min

Play Use assertion functions inside classes

Use assertion functions inside classes

1 min

Play Assign local variables to default generic slots to dry up your code and improve performance

Assign local variables to default generic slots to dry up your code and improve performance

2 mins

Play Know when to use generics

Know when to use generics

2 mins

Play Map over a union type

Map over a union type

1 min

Play Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig

Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig

1 min

Play Use generics to dynamically specify the number, and type, of arguments to functions

Use generics to dynamically specify the number, and type, of arguments to functions

1 min

Play Use 'declare global' to allow types to cross module boundaries

Use 'declare global' to allow types to cross module boundaries

2 mins

Play Turn a module into a type

Turn a module into a type

2 mins

Play Create autocomplete helper which allows for arbitrary values

Create autocomplete helper which allows for arbitrary values

2 mins

Play Use deep partials to help with mocking an entity

Use deep partials to help with mocking an entity

1 min

Play Throw detailed error messages for type checks

Throw detailed error messages for type checks

1 min

Play Create a 'key remover' function which can process any generic object

Create a 'key remover' function which can process any generic object

1 min

Play Use generics in React to make dynamic and flexible components

Use generics in React to make dynamic and flexible components

1 min

Play Create your own 'objectKeys' function using generics and the 'keyof' operator

Create your own 'objectKeys' function using generics and the 'keyof' operator

1 min

Play Write your own 'PropsFrom' helper to extract props from any React component

Write your own 'PropsFrom' helper to extract props from any React component

1 min

Play Use 'extends' keyword to narrow the value of a generic

Use 'extends' keyword to narrow the value of a generic

1 min

Play Use function overloads and generics to type a compose function

Use function overloads and generics to type a compose function

2 mins

Play Decode URL search params at the type level with ts-toolbelt

Decode URL search params at the type level with ts-toolbelt

2 mins

Play Use 'in' operator to transform a union to another union

Use 'in' operator to transform a union to another union

2 mins

Play Derive a union type from an object

Derive a union type from an object

2 mins