如何修正TypeScript的EnvironmentKey类型,使其不同时包含required与defaultValue?
修正TypeScript类型以禁止同时存在
required: true和defaultValue属性 原类型定义允许同时设置required: true和defaultValue属性,不符合需求。要实现仅含required: true、仅含defaultValue、或两者都不含,但绝对不能同时存在的约束,可以通过互斥联合类型来实现:
export type EnvironmentKey = { key: string } & ( // 仅包含key,无额外属性 {} | // 仅允许required: true,禁止defaultValue { required: true; defaultValue?: never; } | // 仅允许defaultValue字符串,禁止required { required?: never; defaultValue: string; } );
类型说明:
{}分支:允许只声明key属性,不附带required或defaultValue{ required: true; defaultValue?: never; }分支:强制required为true,同时通过defaultValue?: never限制该属性不能有任何有效值(等同于禁止存在){ required?: never; defaultValue: string; }分支:强制defaultValue为字符串类型,同时通过required?: never禁止required属性存在
验证示例:
// 合法:仅包含key const onlyKey: EnvironmentKey = { key: "API_URL" }; // 合法:仅设置required: true const onlyRequired: EnvironmentKey = { key: "API_URL", required: true }; // 合法:仅设置defaultValue const onlyDefault: EnvironmentKey = { key: "API_URL", defaultValue: "http://localhost:3000" }; // 类型错误:同时存在required和defaultValue const badBoth: EnvironmentKey = { key: "API_URL", required: true, defaultValue: "http://localhost:3000" };
内容的提问来源于stack exchange,提问作者Josh M.
相关产品推荐
相关产品推荐

