Home > Back-end >  Typsecript, dynamic object keys requires .toString(), why?
Typsecript, dynamic object keys requires .toString(), why?

Time:10-01

Take the below code interface and function:

interface Target {
  name: String;
  value: String;
}

export const validateInput = (target: Target) => {
  let valid: Object = {
    [target.name]: target.value,
  };
  console.log(valid);
};

Why does TS complain about [target.name]?

When I use

[target.name.toString()]

Is works fine.

CodePudding user response:

Object keys should be of the primitive string type, not the String interface which describes the type of the String wrapper object. Note the difference in the case of the first character.

They are similar types but not the same. Every string is a String, but not every String is a string. It is almost always a mistake to use the type named String; change it to string instead and things will start working:

interface Target {
  name: string;
  value: string;
}

export const validateInput = (target: Target) => {
  let valid: Object = {
    [target.name]: target.value, // okay
  };
  console.log(valid);
};

The reason why toString() works is because the return type of that is the primitive string type.

Playground link to code

CodePudding user response:

You're using the object type String instead of string, and objects cannot be used as property keys. If you use string, it works:

interface Target {
  name: string;
  value: string;
}

TypeScript playground

  • Related