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

如何在TypeScript中限定keyof指向string类型属性?

TypeScript约束属性键为字符串类型的解决方案

原代码尝试给对象的指定属性赋值空字符串,但因未约束属性的类型导致编译错误:

function setPropertyToEmptyString<T>(record: T, propertyKey: keyof T) {
  record[propertyKey] = '';
}

报错信息:

Type 'string' is not assignable to type 'T[keyof T]'.
  'T[keyof T]' could be instantiated with an arbitrary type which could be unrelated to 'string'.

解决方案(不新增类型参数)

通过条件映射类型过滤keyof T,只保留属性类型为string的键,同时配合类型断言完成赋值:

function setPropertyToEmptyString<T>(
  record: T,
  propertyKey: keyof { [K in keyof T as T[K] extends string ? K : never]: any }
) {
  record[propertyKey] = '' as T[typeof propertyKey];
}

说明

  1. 属性键过滤:{ [K in keyof T as T[K] extends string ? K : never]: any }会生成一个仅包含T中string类型属性的新类型,取其keyof就得到了符合要求的属性键集合,确保传入的propertyKey只能指向字符串类型的属性。
  2. 类型断言:赋值时用as T[typeof propertyKey]明确告诉编译器,空字符串与目标属性的类型兼容,解决编译器的类型推导问题。

使用示例

const user = { name: 'Alice', age: 25 };
setPropertyToEmptyString(user, 'name'); // 编译正常,name属性被设为空字符串
setPropertyToEmptyString(user, 'age');  // 编译报错,age是number类型,不符合参数要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:00:57