I'm learning about typescript, and I'm struggling with this code below.
const profile = state.currentProfile;
type literalProfile = keyof Partial<Omit<Profile, 'id'>>;
const values: Record<literalProfile, string | undefined> = {
name: '',
avatar: '',
title: '',
subtitle: '',
};
Object.entries(data).forEach((entry) => {
const key = entry[0] as literalProfile;
const value = entry[1];
if (value && profile[key] !== value) {
values[key] = value;
}
});
await this.$axios.patch(`/users/profiles/${profile.id}`, values);
The question is, Is there any way to initialize values as an empty object, like this?
const values: Record<literalProfile, string | undefined> = {};
Because if I do something like this typescript highlight me an error
Type '{}' is missing the following properties from type 'Record<"name" | "title" | "subtitle" | "avatar", string | undefined>': name, title, subtitle, avatar
If I try something like this
let values: Record<literalProfile, string | undefined>;
Then typescript says
Variable 'values' is used before being assigned.
In this line
await this.$axios.patch(`/users/profiles/${profile.id}`, values);
So I don't know how to fix that, any ideas?
Partial<Record<literalProfile, string>>? Or a type assertion to temporarily lie to the compiler about the type of the object while you initialize it? Either way I would prefer to see a minimal reproducible example here suitable for dropping into a standalone IDE like The TypeScript Playground to demonstrate the issue for myself. A self-contained toy example without axios would be nice.