是否有一种重命名安全的方法来检查提供的键字符串是否代表 TypeScript 中的 X?

Is there a renaming-safe way to check if a provided key string represents X in TypeScript?

该函数旨在 NULL 在数据库中为特定用户设置给定属性。如果试图删除用户的phone,则必须有额外的逻辑运行。

常识告诉我,我可以写类似 if (userAttr === 'phone') 的东西,但是,如果将来我们重命名 User 对象属性,并且 phone 更改为类似 phoneNumber 的内容?这个 if 语句将是无用的,它的主体将永远不会被执行。

因此,是否有一种重命名安全的方法来检查提供的 keyof User string 是否表明用户的 phone?

这已经完全符合您的要求:

type User = { name: string, phone: string }
function delete(userId: string, userAttr: keyof User) {
  if (userAttr === 'phone') return 123;
  else return 456;
}

然后,we change the name of the attributephonephoneNumber 然后 TypeScript 会告诉我们:

This condition will always return false since the types "phoneNumber" | "name" and "phone" have no overlap.(2367)