Consider the following three types in which MainType
is union of Type1
and Type2
. If kind
is "kind1"
then data
should be of type {msg: string}
same from Type2
interface Type1 {
kind: "kind1";
data: { msg: string };
}
interface Type2 {
kind: "kind2";
data: { msg2: string };
}
type MainType = Type1 | Type2;
Here is the first way to use it.
function func(obj: MainType) {
switch (obj.kind) {
case "kind1": return obj.data.msg;
case "kind2": return obj.data.msg2;
}
}
The above code gives no error and shows correct autocomplete.
But when we destructure the obj
then it gives error.
function func({kind, data}: MainType) {
switch (kind) {
case "kind1": return data.msg;
case "kind2": return data.msg2;
}
}
The error is
Property
'msg'
does not exist on type'{ msg: string; } | { msg2: string; }'
Maybe its something very basic. But I am new to ts so I can't get how destructuring changes the types. Please explain the reason and also tell is there any way to fix it.
See Question&Answers more detail:os