如何在TypeScript中基于外层对象键前缀限制内层对象的键?
解决方案
要实现每个context对应的内层对象仅包含以该context开头的statusKey,可以利用TypeScript的条件类型和模板字面量类型来筛选键,具体修改如下:
type Context = 'a' | 'b'; type StatusKey = 'aTest' | 'aFinal' | 'bTest' | 'cTest'; interface State { status: { [c in Context]: { // 仅保留以当前context开头的StatusKey成员 [key in Extract<StatusKey, `${c}${string}`>]: { seen: number; total: number; } } } }
关键说明:
${c}${string}是模板字面量类型,用来匹配所有以当前c(即'a'或'b')开头的字符串Extract<StatusKey,${c}${string}>会从StatusKey中提取出符合前缀匹配的键:- 当
c为'a'时,提取出'aTest' | 'aFinal' - 当
c为'b'时,提取出'bTest'
- 当
- 最终生成的
State['status']结构完全符合预期约束,非法的键(比如'a'下的'bTest')会直接被TypeScript报错拦截。
内容的提问来源于stack exchange,提问作者Vishal
相关产品推荐
相关产品推荐

