Ditching Regex in Favor of Typescripts Type pattern checks

🚀 1 min read

Today I learned something quite interesting in Typescript, and I was like whoaa, why was I not using this all these times.

here is the scenario.

checkEmail = (email: string) => {

	// do something with this the email, for now lets just log it
	console.log(email)

}

Now I want that email should always be passed as email format, but this cannot be done unless we add a regex check or a condition inside.

because in above function all of this is valid,.

checkEmail('div') // ✅ Works
checkEmail('div@gmail') // ✅ Works
checkEmail('div@gmail.com') // ✅ Works

but with Typescript we can do this.

checkEmail = (email: `${string}@${string}.${string}`) => {

	// do something with this the email, for now lets just log it
	console.log(email)

}

As you can see we have set the type of argument email as ${string}@${string}.${string} , so we have defined the pattern of the type email can accept.

Now in this case we want to use the checkEmail function, we will get the following error

checkEmail('div') // 🔴 ERROR
checkEmail('div@gmail') // 🔴 ERROR
checkEmail('div@gmail.com') // ✅ Works

This makes the type definition more stronger in the codebase without using any external library or conditions for such checking.

The more I learn TS the more magic it has, Now I cant wait to use this somewhere in my production apps.


X

Did this post help you ?

I'd appreciate your feedback so I can make my blog posts more helpful. Did this post help you learn something or fix an issue you were having?

Yes

No

X

If you'd like to support this blog by buying me a coffee I'd really appreciate it!

X

Subscribe to my newsletter

Join 107+ other developers and get free, weekly updates and code insights directly to your inbox.

  • No Spam
  • Unsubscribe whenever
  • Email Address

    Powered by Buttondown

    Picture of Divyanshu Negi

    Divyanshu Negi is a VP of Engineering at Zaapi Pte.

    X