hi now iam learing typescript and i want to make a function to merge object or string and i use generic to add additional info to the function to can understand mergedObj.name after merge the two objects that’s work fine if i deleted the condition for string but if i try to handle the two cases display error in name
Property ‘name’ does not exist on type ‘string | ({ name: string; } &
{ age: number; })’. Property ‘name’ does not exist on type ‘string’
i understand the mergedObj type here is
string | ({
name: string; } & {
age: number; })
but how i can handle the two cases or multiple type guards with generics ?
type ObjectOrString = object | string;
function merge<T extends ObjectOrString , U extends ObjectOrString>(obj1: T, obj2: U) {
if(typeof obj1 === 'string' || typeof obj2 === 'string'){
return obj1.toString() + obj2.toString();
}
return Object.assign(obj1, obj2);
}
let mergedObj = merge({ name: "zeyad" }, { age: 22 }) ;
console.log(mergedObj.name); // Error Here
/* Property 'name' does not exist on type 'string | ({ name: string; }
& { age: number; })'.
Property 'name' does not exist on type 'string'.ts(2339)
*/
let mergedStr = merge('zeyad', ' moamen');
console.log(mergedStr) // zeyad moamen
>Solution :
You have to disambiguate the type somewhere, for example:
if (typeof mergedObj != 'string')
console.log(mergedObj.name);
removes the error