ts-assert-exists

Assert that a value exists – and remove | null | undefined
from its type
Install
npm install ts-assert-exists
Examples
import assertExists from 'ts-assert-exists';
const twitterToken: string = assertExists(process.env.TWITTER_TOKEN);
or
import assertExists from 'ts-assert-exists';
const twitterToken: string = assertExists(
process.env.TWITTER_TOKEN,
'Twitter token does not exist',
);
Why
Imagine you have a variable that might be undefined:
process.env.APP_NAME;
You want to pass this variable into a function that accepts strings, but TypeScripts gives you an error:
function repeatString(str: string, count: number) {
}
repeatString(process.env.APP_NAME, 5);
To work around this, you could cast the variable with as:
function repeatString(str: string, count: number) {
}
repeatString(process.env.APP_NAME as string, 5);
But what if you forget to specify this environment variable, and it turns out to be undefined? You’ll receive a cryptic runtime error – or, ever worse, a wrong value.
To avoid such issue, use this package:
function repeatString(str: string, count: number) {
}
const definedVariable = assertExists(process.env.APP_NAME);
repeatString(definedVariable, 5);
API
assertExists<Type>(value: Type | null | undefined, messageToThrow?: string): Type;
License
MIT © Ivan Akulov
Based upon the code snippet shared by @Pauan.