Issue
I have these union types:
type Role = 'x' | 'y' | 'z' | 't'
type Entity = { personId: string } | { organizationId: string }
type RoleEntity = { role: 'x', personId: string } | { role: 'y', personId: string } | { role: 'z', organizationId: string } | { role: 'y', organizationId: string }
and this function that inserts a RoleEntity into an array when passing a role and an entity
function laFunc(r: Role, entity: Entity) {
const nard: RoleEntity[] = []
switch (r) {
case 'x':
case 'y': {
if ('personId' in entity) {
nard.push({
role: r,
personId: entity.personId
})
}
}
}
}
But I am getting this error:
Argument of type '{ role: "x" | "y"; personId: string; }' is not assignable to parameter of type 'RoleEntity'.
Type '{ role: "x" | "y"; personId: string; }' is not assignable to type '{ role: "y"; personId: string; }'.
Types of property 'role' are incompatible.
Type '"x" | "y"' is not assignable to type '"y"'.
Type '"x"' is not assignable to type '"y"'.(2345)
How can I fix this?
Solution
Have a union on the role
itself !
type RoleEntity = { role: 'x'|'y', personId: string } | { role: 'z'|'y', organizationId: string }
Answered By - Matthieu Riegler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.