Issue
In the given TypeScript code snippet, I want to create a variable payload of type TypeA | TypeB based on the value of props.value. However, the TypeScript compiler is throwing an error stating "Type '"x"' is not assignable to type 'y'". Can you identify the issue in the code and suggest a modification to resolve this error while maintaining the union type constraint?
type PayloadTypeA = {
value: 'x';
dataA: [],
dataB: {},
};
type PayloadTypeB = {
value: 'y';
dataA: [],
dataB: {},
};
type TypeA = {
value: 'x';
};
type TypeB = {
value: 'y';
};
const propsValue = props.value // can be eithr x or y as type.
// Type '"x"' is not assignable to type "y"
const payload: PayloadTypeA | PayloadTypeB = {
value: propsValue as TypeA | TypeB,
dataA: [],
dataB: {},
};
Solution
You have typing of propsValue wrong, you are typing it as {value: 'y'}
instead of just y
you need to tell typescript, you want type of value
property which is this:
const payload: PayloadTypeA | PayloadTypeB = {
value: propsValue as TypeA['value'] | TypeB['value'] ,
dataA: [],
dataB: {},
};
or just type correctly props
const props: TypeA | TypeB; //this can be some bigger type, but type of "value" must match
const propsValue = props.value;
const payload: PayloadTypeA | PayloadTypeB = {
value: propsValue,
dataA: [],
dataB: {},
};
Answered By - Wraithy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.