I'm trying to make a typed flow of the assigning the JSON snapshot of the instance to the instance itself by setting the snapshot's values to the instance's properties. I used the keyof
utility type to get the union type of the snapshot object keys. These keys are the same like the property names of the instance so it works without any problem in JS.
However at the stage of assigning values from the snapshot to the instance properties TS throws a weird error about the:
/**
Type 'string | boolean' is not assignable to type 'never'.
Type 'string' is not assignable to type 'never'.ts(2322)
*/
I don't understand what's wrong here because keys should be the same or, maybe, I just missed something. Could someone, please, give to me some advice where did I made some mistake?
Here is the more detailed code example:
export type AttachmentModelJsonType = {
file: string,
name: string,
preview: string,
uploading: boolean,
optimistic: boolean,
serverAttachmentId: string,
};
export class AttachmentModel {
file: string;
name: string;
preview: string;
uploading = false;
optimistic = false;
serverAttachmentId: string | null = null;
updateFromJson = (data: AttachmentModelJsonType) => {
(Object.keys(data) as Array<keyof AttachmentModelJsonType>).forEach(key => {
// TS compiler throws an error about:
/** Type 'string | boolean' is not assignable to type 'never'.
Type 'string' is not assignable to type 'never'.ts(2322)
*/
this[key] = data[key];
});
};
}
Thanks for any help!
P.S. Here is the code example where you can check this error: