I have a function that formats some data from a type to another. Basically changes some case and flats some fields.
This is my code:
const formatData = (data: Login): LoginFormatted => {
return {
Date: data.date,
UserInfo: {
name: data.user.name,
email: data.user.email
},
...data.otherFields
};
};
const doThat = (data: Login) => {
const dataFormatted = formatData(data);
return dataFormatted;
};
const dataFormatted = doThat({
date: "2000-12-01",
user: {
name: "Mary",
email: "mary.lorem@something.com"
},
otherFields: { lastname: "Snow", city: "Berlin" }
});
And my types:
export type Login = {
date: string;
user: {
name: string;
email: string;
};
otherFields?: { [key: string]: string };
};
export type LoginFormatted = {
Date: string;
UserInfo: {
name: string;
email: string;
};
} & { [key: string]: string };
HERE the working code
I get a TypeScript error in formatData:
Type '{ Date: string; UserInfo: { name: string; email: string; }; }' is not assignable to type 'LoginFormatted'. Type '{ Date: string; UserInfo: { name: string; email: string; }; }' is not assignable to type '{ [key: string]: string; }'. Property 'UserInfo' is incompatible with index signature. Type '{ name: string; email: string; }' is not assignable to type 'string'.
What am I doing wrong?
I read these questions (How to define Typescript type as a dictionary of strings but with one numeric "id" property, Property is not assignable to string index in interface), and I tried to modify my code like this but it still doesn't work:
export interface Login {
date: string;
user: {
name: string;
email: string;
};
otherFields?: Other;
}
export type LoginFormatted = {
Date: string;
UserInfo: {
name: string;
email: string;
};
} & Other;
interface Other {
[key: string]: string;
}