如何在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
相关产品推荐
相关产品推荐

