Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

generics in typescript with typeof for type guard

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading