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 suggesst 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!
Thanks in advance!
>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;
};