Home > Blockchain >  How to find whether a value is a Typescript Type
How to find whether a value is a Typescript Type

Time:08-08

I created a type called CSSControl which describes a few control types. Some of the controls have additional properties as well. Here is a description of the CSSControl:

type CSSControl = "Button" | "TextField" | "MultiSelect" | "CheckBox" | "Radio" 

These controls are further categorized into another category i.e. whether they can be rendered with additional styles, set by a boolean flag. The textfield, buttons and multiselect are the controls that can have additional styling applied. So, I created another type to reflect that feature like this;

type CSSAdditional = "LB_Button" | "HD_TextField" | "MS_MultiSelect";

Finally, I create the control types like this:

type TextFieldControl = {
  control: "TextField",
  style: "HD_TextField",
}

type MultiSelectControl = {
  control: "TextField",
  style: ""MS_MultiSelect"",
}

The controls are described from JSON so I parse it out and then have to determine which of the controls are being described, here is an example:

{
  "page": { 
     "name": "TextField",
     "additionalStyles": "true",
     "productOptions: "MultiSelect"
  }
}  

Here you can see that additional style is turned on. I am able to parse the data into an object, but I am wondering how to compare the name field and the product options, since these are text strings and the CSSAdditional is a type. I want to be able to be able to do something like:

const page = JSON.parse(pageStr);
const fieldControl  = page.name;
const applyAdditionalStyles = page.additionalStyles;
if((fieldControl is a type of CSSAdditional) && applyAdditionalStyles){
   // then apply additional styles
}

I don't know how to compare the fieldControl with one of the types CSSAdditional.

Please help

CodePudding user response:

You can define an array with the possible values first:

const CSSAdditionalValues = ["LB_Button", "HD_TextField", "MS_MultiSelect"] as const;

Using as const here to make TypeScript infer the type of CSSAdditionalValues as literally ["LB_Button", "HD_TextField", "MS_MultiSelect"].

That means we can then get the original CSSAdditional type back like this:

type CSSAdditional = (typeof CSSAdditionalValues)[number];

And because you have an array of the possible values, you can use it to check if a value is the type CSSAdditional:

if (CSSAdditionalValues.includes(fieldControl) && applyAdditionalstyles) {
    // ...
}
  • Related