You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:25:40