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.
>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.