简体   繁体   English

是否有更简洁的 Typescript 习惯用法用于在运行时未定义值的情况下引发错误?

[英]Is there a neater Typescript idiom for throwing an error in case a value is undefined at runtime?

I'm using dotenv to load some values are runtime.我正在使用 dotenv 加载一些运行时的值。 I want to throw an error in the case the value is undefined.如果值未定义,我想抛出错误。 Is there a neater way of doing this in Typescript than the following?在 Typescript 中是否有比以下更简洁的方法?

    dotenv.config()
    if (process.env.USERNAME == undefined) {
        throw new Error("USERNAME is undefined")
    }
    let username:string = process.env.USERNAME

Node.js has the assert module for purposes like this, though @types/assert fails to declare the functions in this module as type predicates , so the assertions will also need to be done separately using TypeScript at compile-time. Node.js 具有用于此类目的的assert模块,尽管@types/assert未能将此模块中的函数声明为type predicates ,因此还需要在编译时使用 TypeScript 单独完成断言。

import assert from 'assert';
import dotenv from 'dotenv';

dotenv.config();

assert.notStrictEqual(process.env.USERNAME, undefined, 'USERNAME is undefined');

let username: string = process.env.USERNAME;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM