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

Which properties can I check for in TypeScript

When using TypeScript, I realized that I don’t fully understand how property checking works. In the example below I do not understand why checking for .bold works but but checking for .type doesn’t.

type CustomText = {
    bold: boolean;
};

type TitleElement = { type: 'title'; children: string };

type Element = TitleElement | CustomText;

const el: Element = {
  bold: true,
}

if (!el.bold) {
  console.log("does not have bold")
}

if (!el.type) { // <- compiler error
  console.log("does not have type")
}

>Solution :

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

Looks like, Typescript already knows that the element you have entered is of what type (CustomText) because it is statically assigned in your code. Had it been something dynamic, TS would have complained for both.

For example:

const getElem = () => {
  if(Math.floor((Math.random() * 10) + 1)%2)
   {
      const x : TitleElement = { name: 'title', children: 'x' };
      return x;
   } 
  else{
      const x : CustomText = { bold: false };
      return x;
 
  }
}

type CustomText = {
    bold: boolean;
};

type TitleElement = { name: 'title'; children: string };

type Element2 = TitleElement | CustomText;

let el: Element2 = getElem();

if (!el.bold) {

  console.log("does not have bold")
}

if (!el.name) { // <- compiler error
  console.log("does not have type")
}

Playground

The purpose of Union is that it allows properties from all the union participants. You can easily access any property present in both CustomText and TitleElement. TS should throw an error and it will . If you do something like below, TS will throw errors in both the if conditions.

type CustomText = {
    bold: boolean;
    both : string;
};

type TitleElement = { name: 'title'; children: string, both : string; };

type Element2 = TitleElement | CustomText;

const el: Element2 = {
  bold: true,children: 'sing' 
}

if (!el.bold) {
  console.log("does not have bold")
}

if (!el.name) { // <- compiler error
  console.log("does not have type")
}

if (!el.both) { // <- compiler error
  console.log("does not have type")
}

This happens cause now again TS is not sure of the type of Element2, and it cannot allow you to access a property not present in both.

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