1

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 :)

behzad k.
  • 49
  • 7
  • 2
    You can store your state mapping as an object, an get the value you need with [], like : `let obj = { 0: 'no', 1:'yes', 2: 'undefined'}; let str = obj[input[1]]` – Lk77 Nov 30 '22 at 16:47
  • I am a little confused by your logic. you say "String with a length of 3" but it appears to be a sting of length 1, or an int. also, why are you using 3 different strings to represent the same thing? 'no', '0', 'locked'. seems redundant. why not 2 or 1 of those strings? – Rick Nov 30 '22 at 16:51
  • that was just an example for the char at the second position – behzad k. Dec 05 '22 at 11:36

2 Answers2

1

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

DonCarleone
  • 544
  • 11
  • 20
0
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

Dimava
  • 7,654
  • 1
  • 9
  • 24