Search code examples
typescriptkeyrenametype-safety

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


  • I have a User object, which has some attributes such phone.
  • I also have a function like this: delete(userId: string, userAttr: keyof User)

The function is intended to set NULL in the database a given attribute for a specific user. If trying to delete the user's phone, there is extra logic that must be run.

What common sense tells me is that I can just write something like if (userAttr === 'phone'), but, what happens if in the future we do a renaming of the User object attributes, and phone is changed to something like phoneNumber? This if statement will be useless and its body will never be executed.

Therefore, is there a renaming-safe way to check if a provided keyof User string is the one that indicates the user's phone?


Solution

  • This already works exactly as you want it to:

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

    then later, we change the name of the attribute from phone to phoneNumber then TypeScript will tell us:

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