Issue
Imagine this scenario of code:
type A = {
keyOne: string;
keyTwo: string;
};
type B = {
keyThree: string;
keyFour: string;
};
type C = {
unionKey: A | B;
keyFive: string;
};
type CA = {
unionKey: A;
keyFive: string;
};
type CB = {
unionKey: B;
keyFive: string;
};
const obj: C = {} as C;
if ('keyOne' in obj.unionKey) {
obj.unionKey.
}
const handleType = (obj: C): CA | CB => {
if ('keyOne' in obj.unionKey) {
return obj as CA;
} else return obj as CB;
};
const result = handleType({
unionKey: {
keyThree: 'sdfsd',
keyFour: 'sadfasd',
},
keyFive: 'sdfsd',
});
result.unionKey. // TS is get confused here and could not suggest me correct type which I'm looking for (keyThree & keyFour)
Consider having obj
, how can I check the type on unionKey
to see which type it follows? If it is type A
I want to do work X, and if it is B
I want to do work Y.
The issue is the comparing JS value to TS type!
Solution
Change your function to use a generic type, and the type will fall pass.
eg..
function handleType<T extends C>(obj: T) {
if ('keyOne' in obj.unionKey) {
return obj;
} else return obj;
};
Answered By - Keith
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.