TypeScript如何约束属性值为另一属性有效值或与另一属性值相同?
问题1:约束
active为steps数组中的某一项 可以通过泛型接口关联steps和active的类型,让active的取值严格限定在steps的元素范围内:
interface Progress<T extends string> { steps: T[], active: T } // 正确示例:active是steps中的元素 const p1: Progress<'foo' | 'bar' | 'baz'> = { steps: ['foo', 'bar', 'baz'], active: 'foo' }; // 错误示例:active不在steps中,TypeScript会抛出类型错误 const p2: Progress<'foo' | 'bar' | 'baz'> = { steps: ['foo', 'bar', 'baz'], active: 'bob' };
如果不想手动声明联合类型,可借助as const让TypeScript自动推导数组的字面量元素类型:
const steps = ['foo', 'bar', 'baz'] as const; type StepType = typeof steps[number]; const p3: Progress<StepType> = { steps, active: 'bar' }; // 正确 const p4: Progress<StepType> = { steps, active: 'bob' }; // 错误
as const会将数组转为只读的字面量数组,确保TypeScript推导出具体的字符串类型,而非宽泛的string。
问题2:约束
p1与p2取值相同 同样用泛型接口绑定两个属性的类型,强制它们的取值必须一致:
interface Twins<T extends string> { p1: T, p2: T } // 正确示例:p1和p2取值相同 const t1: Twins<'bob'> = { p1: 'bob', p2: 'bob' }; // 错误示例:p2与p1取值不同,TypeScript会报错 const t2: Twins<'bob'> = { p1: 'bob', p2: 'alice' };
也可以让TypeScript自动推导泛型类型,无需手动指定:
const t3: Twins<string> = { p1: 'bob', p2: 'bob' }; // 正确 const t4: Twins<string> = { p1: 'bob', p2: 'alice' }; // 错误
若需要更严格的类型约束(比如限定为某个固定字符串),可结合typeof和字面量类型:
const fixedName = 'bob' as const; const t5: Twins<typeof fixedName> = { p1: fixedName, p2: fixedName }; // 正确 const t6: Twins<typeof fixedName> = { p1: fixedName, p2: 'alice' }; // 错误
内容的提问来源于stack exchange,提问作者wensveen
相关产品推荐
相关产品推荐

