You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

ts-assert-exists

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-assert-exists

Assert that a value exists – and remove `| null | undefined` from its type

1.0.5
latest
Source
npmnpm
Version published
Weekly downloads
617
7.49%
Maintainers
1
Weekly downloads
 
Created
Source

ts-assert-exists

npm Travis

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);
// 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

import assertExists from 'ts-assert-exists';

const twitterToken: string = assertExists(
    process.env.TWITTER_TOKEN,
    'Twitter token does not exist',
);
// 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:

function repeatString(str: string, count: number) {
    // ...
}

repeatString(process.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:

function repeatString(str: string, count: number) {
    // ...
}

// Don’t do this!
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.

Keywords

typescript

FAQs

Package last updated on 22 Mar 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts