TypeScript无法识别函数内的变量前置检查,求解决方案
解决TypeScript无法识别跨函数变量存在性检查的问题
TypeScript默认不会追踪跨函数的类型窄化逻辑,所以直接抽离检查函数后,TS无法判断process.env.DRIVER_PATH已经被排除了undefined的可能。可以用以下两种方案解决:
方案一:使用类型断言函数
修改检查函数为类型断言函数,明确告诉TS:当函数正常返回时,process.env.DRIVER_PATH一定是string类型:
function envChecks(): asserts process.env is { DRIVER_PATH: string } { if (!process.env.DRIVER_PATH) { throw new Error('Environment variable DRIVER_PATH is not set'); } }
调用后TS会自动更新process.env的类型,后续使用不再报错:
import path from 'path'; export async function thisDoesSomething() { envChecks(); const pathToDriver = path.resolve(process.env.DRIVER_PATH); // 类型安全 // ...更多代码 }
方案二:让检查函数返回已校验的变量
将检查逻辑和变量获取合并,直接返回经过校验的string类型变量,使用时直接接收:
function getDriverPath(): string { const driverPath = process.env.DRIVER_PATH; if (!driverPath) { throw new Error('Environment variable DRIVER_PATH is not set'); } return driverPath; }
使用方式:
import path from 'path'; export async function thisDoesSomething() { const driverPath = getDriverPath(); const pathToDriver = path.resolve(driverPath); // 无类型错误 // ...更多代码 }
内容的提问来源于stack exchange,提问作者user12477310
相关产品推荐
相关产品推荐

