简体   繁体   中英

Is there a way to “signal” type narrowing to TypeScript from an earlier null/undefined check?

I'm loading a few environment variables into my Node & Express app using dotenv and a lot of these values are critical to the app's function so before doing anything I validate these variables to make sure they're included and that they have the correct type, otherwise I throw an error and stop the server from starting.

I now need to use these variables down the line, but TypeScript does not recognize that I have narrowed the types so it prevents me from doing things like process.env.test.includes (without optional chaining or nearby type assertion) saying Object is possibly null or undefined (I have strict mode enabled). I know in some cases it'll recognize that I have narrowed the type if I do type checks but I'm guessing this is not nearby enough to the code for it to pick up on this. Is there any way to signal that I have already narrowed the type from string | null | undefined string | null | undefined string | null | undefined to just string , for example, or do I have to continue to use the optional chaining operator?

You can use the non-null assertion operator ! to tell TypeScript that you know better, that it should never be null/undefined:

process!.env!.test!.includes

This is of course assuming that any of the keys in the chain could return null/undefined, but you probably don't need to use the operator on every single accessor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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