I'm currently working on creating a code that will generate a discriminated union for each member of a type and a function that allows for accepting an object of that type along with an instance of one of the union members.
Here's the progress I've made so far:
interface RickAndMortyCharacter {
species: string;
origin: {
name: string;
url: string;
};
}
type RickAndMortyCharacterChange = {
[Prop in keyof RickAndMortyCharacter]: {
updatedProps: Prop;
newValue: RickAndMortyCharacter[Prop];
};
}[keyof RickAndMortyCharacter];
function applyPropertyChange(
state: RickAndMortyCharacter,
payload: RickAndMortyCharacterChange
) {
// Error on this line
state[payload.updatedProps] = payload.newValue;
return state;
}
You can also try it out with TypeScript on the playground
When using TypeScript, I encountered the following error message:
Type 'string | { name: string; url: string; }' is not assignable to type 'string & { name: string; url: string; }'. Type 'string' is not assignable to type 'string & { name: string; url: string; }'. Type 'string' is not assignable to type '{ name: string; url: string; }'.(2322)
Interestingly, upon hovering over the RickAndMortyCharacterChange
type, I noticed that the declared type was as follows:
type RickAndMortyCharacterChange = {
updatedProps: "species";
newValue: string;
} | {
updatedProps: "origin";
newValue: {
name: string;
url: string;
};
}
This declaration seems accurate to me, especially considering that TypeScript prevents me from writing these examples:
const s: RickAndMortyCharacterChange = {
updatedProps: "origin",
newValue: "bonjour"
};
const s2: RickAndMortyCharacterChange = {
updatedProps: "species",
newValue: {
name: "Hello",
url: "Hoi"
}
}
I have recently used a similar method in an Angular project which worked flawlessly. I am puzzled as to why TypeScript is flagging an issue here.