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

TypeScript中extends子句结合keyof时泛型参数未正确收窄问题

TypeScript类型约束疑问:为何keyof R未被正确收窄为string?

这是某问题的纯类型简化实现,示例更简洁:

type TypedRouter<P extends string> = any

type Test<R> = R extends {
  [key: string]: any;
}
  ? {
      [P in keyof R]: TypedRouter<P>
//                                ^ 'string | number | symbol' is not assignable to type 'string'
    }
  : never;

疑问:既然已经通过R extends {[key: string]: ...}约束了R的结构,那么keyof R应该为string,为何P in keyof R中的P类型是string | number | symbol而非string?

目前的临时解决方案是使用&操作符手动收窄类型:

type Test<R> = R extends { [key: string]: any }
  ? {
      [P in keyof R]: TypedRouter<P & string>;
    }
  : never;

内容的提问来源于stack exchange,提问作者Eliav Louski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:54:53