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

TypeScript泛型:如何确保记录的键始终为字符串?

解决TypeScript隐式转换symbol到string的类型提示问题

问题根源

当前func函数的泛型约束K extends keyof Row允许K是string、number或symbol类型的对象键,但模板字符串会尝试把这些类型隐式转为字符串——当K是symbol类型时,运行时必然出错,因此TypeScript触发了类型提示。

解决方案

我们需要明确限制泛型K只能是目标对象中字符串类型的键,有两种简洁的实现方式:

方式1:直接通过交叉类型约束

修改func的泛型定义,让K同时满足是string和Row的键:

const func = <Row extends object, K extends string & keyof Row>(rows: Row, ace: K) => {
  return `hello-${ace}-ws`;
}

方式2:用Extract工具类型筛选字符串键

借助TypeScript内置的Extract工具类型,从keyof Row中提取出所有字符串类型的键:

const func = <Row extends object, K extends Extract<keyof Row, string>>(rows: Row, ace: K) => {
  return `hello-${ace}-ws`;
}

可选:同步优化TableProps类型

如果你的TableProps类型也需要确保ace是字符串键,可以同步更新它的泛型约束:

type TableProps<Row extends Record<string, unknown>, K extends Extract<keyof Row, string>> = {
  rows: Array<Row>,
  ace: K,
}

经过以上修改,TypeScript会明确认定ace始终是字符串类型,既消除了类型提示,也避免了运行时的潜在错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:52:53