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

compare js object key to see if is the same typescript type

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!

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

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;
};

TS Playground

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