ts-assert-exists
Assert that a value exists – and remove
| null | undefined
from its type
Install
npm install ts-assert-exists
Examples
; ;// Type of `process.env.TWITTER_TOKEN` is `string | undefined`.// `assertExists` will cast `process.env.TWITTER_TOKEN` to `string`// and throw if `process.env.TWITTER_TOKEN` would be null or undefined.
or
; ;// Type of `process.env.TWITTER_TOKEN` is `string | undefined`.// `assertExists` will cast `process.env.TWITTER_TOKEN` to `string`// and throw an error with “Twitter token does not exist”// if `process.env.TWITTER_TOKEN` would be null or undefined.
Why
Imagine you have a variable that might be undefined:
process.env.APP_NAME; // Has a type of `string | undefined`
You want to pass this variable into a function that accepts strings, but TypeScripts gives you an error:
repeatStringprocess.env.APP_NAME, 5;// TypeScript: type 'string | undefined' is not assignable to type 'string'
To work around this, you could cast the variable with as:
// Don’t do this!repeatStringprocess.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:
;repeatStringdefinedVariable, 5;
API
assertExistsvalue: Type | null | undefined, messageToThrow?: string: Type;
License
MIT © Ivan Akulov
Based upon the code snippet shared by @Pauan.