Home > Blockchain >  Which properties can I check for in TypeScript
Which properties can I check for in TypeScript

Time:03-04

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")
}

CodePudding user response:

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

  • Related