In this short guide, I will introduce you to the Definite Assignment Assertion feature in typescript and demonstrate to you an interesting use case to implement this feature.
When working with the Stripe API in one of my Next.js & Typescript projects, I came across an error where typescript didn't recognize my environment variable as a string. It later displayed the error message below.
The solution in this case is to use the "!" symbol which is a feature in Typescript known as the definite assignment assertion.
As defined in the official Typescript Documentation, the definite assignment assertion feature is used to tell the compiler that the variable assigned is indeed valid for all intents and purposes, even if Typescript's analyses cannot detect so.
The "!" symbol is used and is declared after an instance property and/or variable declarations.
With the definite assignment assertion, we can assert that indeed in this case we have environment variables (
process.env.STRIPE_SECRET_KEY) in string format and there is nothing to worry about.
This workaround still leaves us with weaker type safety since any misconfiguration (in our case the environment variables) could lead to errors that cannot be caught at compile time. These errors can only be caught at runtime which beats the logic of having a strict and functional type checking system. With this in mind it's your responsibility to ensure correctness.
It's also good to note that previous Typescript versions used the "!" symbol as a non-null assertion operator. You can read more about this in the Typescript Documentation about Non-null assertion operator.
Thank you for reading this far and happy coding!