TypeScript如何限制函数参数仅匹配多个接口中的某一个,禁止混合字段
问题原因
当前写法不报错是TypeScript联合类型的默认特性:只要传入的对象满足联合类型中任意一个成员的结构要求,即使携带其他成员的属性也不会触发类型错误,对象字面量的额外属性校验在联合类型场景下默认不会拦截混合属性的情况。
解决方案
方案1:通用严格互斥联合工具(推荐,适合接口可扩展场景)
可以定义一个StrictUnion泛型工具,自动给联合类型的每个成员加上其他所有成员属性的never类型限制,只要传入其他接口的属性就会触发类型冲突报错。
完整实现代码如下:
interface Interface1 { one: string } interface Interface2 { two: string } interface Interface3 { three: string } // 严格互斥联合工具类型 type UnionKeys<T> = T extends T ? keyof T : never; type StrictUnionHelper<T, TAll> = T extends any ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never; type StrictUnion<T> = StrictUnionHelper<T, T> // 替换原来的联合类型定义 type ManyInterfacesInOneType = StrictUnion<Interface1 | Interface2 | Interface3>; function bla(param1: ManyInterfacesInOneType) { }
方案2:手动标记互斥属性(适合接口数量少的场景)
如果接口数量少且后续不会频繁变动,可以手动给每个接口加上其他接口属性的never限制,效果和通用工具一致:
interface Interface1 { one: string two?: never three?: never } interface Interface2 { two: string one?: never three?: never } interface Interface3 { three: string one?: never two?: never } type ManyInterfacesInOneType = Interface1 | Interface2 | Interface3; function bla(param1: ManyInterfacesInOneType) { }
效果验证
- 合法调用:
bla({one: ''})、bla({two: ''})、bla({three: ''})均正常通过类型校验 - 非法调用:
bla({one: '', two: ''})、bla({one: '', two: '', three: ''})都会抛出类型错误,提示传入的属性不符合类型要求
内容的提问来源于stack exchange,提问作者Aegletes
相关产品推荐
相关产品推荐

