Home > Enterprise >  Simplifying Typescript If statements
Simplifying Typescript If statements

Time:12-01

i am relative new to typescript (coming from java) and i have currently the following problem:

Given: String with a length of 3, it can only contain the charts '0', '1' and '2'. Each of them are representing a different state. Lets assume here the following: '0' -> 'no', '1' -> 'yes', '2' -> 'unknown'. What is the most readable and simplified way to implement it? Currently i am just using simple if functions which are checking what state i have at every index, like:

let state: 'no' | 'yes' | 'unknown';
  if (input[1] === '0') {
    state = 'locked';
  } else if (input[1] === '1') {
    state = 'unlocked';
  } else {
    state = 'unknown';
  }
Because i am still new into Typescript i don't know if there is a better way to do that in Typescript :/

Thanks :)

CodePudding user response:

Do you mean a switch statement?
You can throw it in a for-loop like this:

let state: 'no' | 'yes' | 'unknown';
for (let i = 0; i < input.length; i  ) {
    switch(input[i]) { 
       case '0': { 
          state = 'locked';
          break; 
       } 
       case '1': { 
          state = 'unlocked';
          break; 
       } 
       default: { 
          state = 'unknown';
          break; 
       } 
    } 
}

You can read more about TS switch statements here https://www.tutorialsteacher.com/typescript/typescript-switch

CodePudding user response:

const mapping = {
//    ^?
    '0': 'locked',
    '1': 'yes',
    '2': 'unknown'
} as const;
// const mapping: {
//     readonly '0': "locked";
//     readonly '1': "yes";
//     readonly '2': "unknown";
// }

let y = mapping['0']
//  ^?
// let y: "locked"


// this generic basicaly splits the variants for different constants same as mapping[x]
function mapState<K extends keyof typeof mapping>(k: K) {
    return mapping[k]
}

let x = mapState('1')
//  ^?
// let x: "yes"

let a: '1' | '2' = Math.random() < 0.5 ? '1' : '2'
//  ^?
// let a: "1" | "2"
let z1 = mapping[a]
//  ^?
// let z1: "yes" | "unknown"
let z2 = mapState(a)
//  ^?
// let z2: "yes" | "unknown"

Playground

If you are interested how far can that used, there is document.createElement function which returns HTMLImageElement from document.createElement('img') and around 50 other types for other args

  • Related