You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中缩小process.env的键范围且不修改值?

TypeScript中process.env与自定义接口类型不匹配问题

问题代码及报错

以下代码尝试将process.env传入接收UnvalidatedInputs类型参数的函数:

interface UnvalidatedInputs {
  A: string | undefined;
  B: string | undefined;
}

interface ValidatedInputs {
  a: string;
  b: number;
}

export function validateInputs(processEnv: UnvalidatedInputs): ValidatedInputs {
  const a = processEnv.A;
  const b = Number(processEnv.B);
  if (a === undefined || Number.isNaN(b)) {
    throw new Error("invalid inputs");
  }
  return { a, b };
}

export const VALIDATED_INPUTS = validateInputs(process.env);

TypeScript类型检查时抛出错误:

Argument of type 'ProcessEnv' is not assignable to parameter of type 'UnvalidatedInputs'.
  Type 'ProcessEnv' is missing the following properties from type 'UnvalidatedInputs': A, B(2345)

关于NodeJS.ProcessEnv的定义

实际上ProcessEnv的类型定义包含所有字符串类型的键,"A"和"B"属于其子集,大致定义如下:

interface ProcessEnv {
  [key: string]: string | undefined;
  TZ?: string;
}

解决方法:通过标识函数缩小类型

使用一个无操作的标识函数,让TypeScript识别并缩小process.env的键集合范围,即可解决类型不匹配问题:

type Dict<K extends string> = {
  [P in K]: string | undefined;
};

export function identityNarrow<K1 extends string, K2 extends K1>(
  input: Dict<K1>
): Dict<K2> {
  return input;
}

export const NARROWED_PROCESS_ENV: Dict<"A" | "B"> = identityNarrow(
  process.env
);

内容的提问来源于stack exchange,提问作者bossylobster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 09:42:45