Notes

Pass objects as parameters with their types specified and default values

Edit on GitHub

Typescript
2 minutes

Passing arguments as an object

Passing arguments to a function as an object makes the meaning much more clear from the name of the properties and the order in which you pass them no longer matters.

1const createUser = (username, date, isAdmin, isSubscribed) => {
2  // Create user
3}
4
5createUser('Abeeha', '2021-12-23', false, true)

vs.

1const createUser = ({ username, date, isAdmin, isSubscribed }) => {
2  // Create user
3}
4
5createUser({ username: 'Abeeha', date: '2021-12-23', isAdmin: false, isSubscribed: true })

Parameter objects and TypeScript

Now, coming to the TS bits, here’s the interface of a request to an API call

1interface PopularUserRequest {
2  Application: 'uk' | 'us'
3  Sex: 'm' | 'f' | 'notSet'
4  Count: number
5  ShowMilitaryOnly: boolean
6}

Here’s how you’d pass

1export default async function fetchPopularUsers({ Application, Sex, Count, ShowMilitaryOnly }: PopularUserRequest) {
2  // code goes here
3}

And here’s how you’d pass the object param with it’s type specified and default values

1export default async function fetchPopularUsers({
2    Application: 'uk',
3    Sex: 'notSet',
4    Count: 52,
5    ShowMilitaryOnly: false,
6  }: PopularUserRequest,
7) {
8  // code goes here
9}

Here’s how you’d call this function and pass an object as parameter

1fetchPopularUsers({
2  Application: 'uk',
3  Sex: 'notSet',
4  Count: 52,
5  ShowMilitaryOnly: false,
6})