TypeScript如何实现“存在某键则必存在对应关联键”的类型约束?
简洁实现MyType的类型约束
可以通过封装一个成对属性约束的工具类型来简化实现,避免重复写繁琐的交叉/联合逻辑,具体如下:
步骤1:定义通用成对约束工具类型
这个工具类型可复用,用来实现「要么同时包含两个属性,要么都不包含」的约束:
// 工具类型:要么同时拥有K1和K2,要么都没有 type WithPair<K1 extends string, K2 extends string, PropType = unknown> = | { [Key in K1 | K2]: PropType } // 同时包含两个属性 | { [Key in K1 | K2]?: never }; // 两个属性都不出现(或设为never确保无法单独赋值)
步骤2:组合出MyType
通过交叉工具类型与必填的foo属性,快速实现需求:
type MyType = { foo: unknown; // 替换为你实际需要的foo属性类型 } & WithPair<'barPre', 'barPost'> & WithPair<'quxPre', 'quxPost'>;
类型验证
- 合法示例:
// 仅包含必填foo const valid1: MyType = { foo: "hello" }; // 包含foo + 完整bar成对属性 const valid2: MyType = { foo: 123, barPre: true, barPost: false }; // 包含foo + 完整qux成对属性 const valid3: MyType = { foo: {}, quxPre: "pre", quxPost: "post" }; // 包含foo + 两组完整成对属性 const valid4: MyType = { foo: [], barPre: 0, barPost: 1, quxPre: null, quxPost: undefined }; - 非法示例(TypeScript会报错):
// 缺少barPost const invalid1: MyType = { foo: "", barPre: "oops" }; // 缺少quxPre const invalid2: MyType = { foo: 0, quxPost: "missing pre" };
如果后续需要新增类似的成对属性约束,只需追加& WithPair<'xxxPre', 'xxxPost'>即可,无需重复编写复杂的联合逻辑,非常简洁。
内容的提问来源于stack exchange,提问作者J. Hesters
相关产品推荐
相关产品推荐

