Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typsecript, dynamic object keys requires .toString(), why?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[target.name.toString()]

Is works fine.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading