TypeScript如何创建与另一属性值关联的泛型union联合类型
实现方案
你可以通过两种方式实现属性间的关联约束:
方案1:泛型工具类型(支持任意数值范围)
先定义工具类型用来生成1 ~ N的数字联合类型:
type NumberRange<N extends number, Result extends number[] = []> = Result['length'] extends N ? Result[number] : NumberRange<N, [...Result, [...Result, 1]['length']]>
修改你的Props为泛型类型,绑定两个属性的类型关联:
type Props<T extends number> = { numberOfPoints: T; activeItem: NumberRange<T>; }
使用示例
// 显式指定泛型参数 const validProps: Props<3> = { numberOfPoints: 3, activeItem: 2 // 类型合法 } const invalidProps: Props<3> = { numberOfPoints: 3, activeItem: 4 // TS报错:类型4不能分配给类型1 | 2 | 3 } // 自动推导泛型,无需手动传参 function defineProps<T extends number>(props: Props<T>) { return props; } const autoProps = defineProps({ numberOfPoints: 5, activeItem: 3 // 自动推导activeItem类型为1 | 2 | 3 | 4 | 5,合法 })
方案2:手动联合类型(适用固定取值范围场景)
如果numberOfPoints只有少数几个固定取值,可以直接写枚举式联合类型,可读性更高,无需复杂类型体操:
type Props = | { numberOfPoints: 1; activeItem: 1 } | { numberOfPoints: 2; activeItem: 1 | 2 } | { numberOfPoints: 3; activeItem: 1 | 2 | 3 } | { numberOfPoints: 4; activeItem: 1 | 2 | 3 | 4 }
内容的提问来源于stack exchange,提问作者Mohammad Reza Ghasemi
相关产品推荐
相关产品推荐

