Home to enum? or not
Post
Cancel

to enum? or not

recently i got into a strange issue when using enum, using an example of a card deck where i would want a deck to have certain suits as params

1
2
3
4
5
6
7
8
export enum cardSuits {
  diamond,
  club,
  hearts,
  spades,
}

console.log(Object.keys(cardSuits))

this return us:

1
["0", "1", "2", "3", "diamond", "club", "hearts", "spades"]

hmm thats strange, but i guess if we use string enums we can:

1
2
3
4
5
6
7
8
export enum cardSuits {
  diamond = "diamond",
  club = "club",
  hearts = "hearts",
  spades = "spades",
}

console.log(Object.keys(cardSuits))

returned us as

1
["diamond", "club", "hearts", "spades"]

great! but this isnt really recommended since if we want to use it in javascript we have to import the typings

1
2
3
4
5
getSuits("diamond") //wont work

import {cardSuits} from "suits"
getSuits(cardSuits.Diamond)

the alternative is usually is to use type

1
2
type cardSuits = "diamond" | "club" | "hearts" | "spades"
let suits: cardSuits = "diamond" //OK

but this doest allow us to iterate through the suits

1
2
3
const suits = ["diamond", "club", "hearts", "spades"] as const
type cardSuits = typeof suits[number]
const suit4 = suits.map((v)=>"4"+v) //["4diamond", "4club", "4hearts", "4spades"]

but can we do better? what if there are point system involve for the suits? (e.g us wanting to rank them in bridge order - clubs diamond hearts spade)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const cardSuits = {
  club: 0,
  diamond: 1,
  hearts: 2,
  spade: 3 
} as const // prevent override!

type possibleSuits = keyof typeof cardSuits

function compareSuits(suit1: possibleSuits, suit2:possibleSuits){
  if(cardSuits[suit1] < cardSuits[suit2]){
    console.log(`${suit1} is smaller than ${suit2}`)
  }
  else{
    console.log(`${suit1} is bigger than ${suit2}`)
  }
}

compareSuits("club","hearts")

//convert to array to use iteration
const cardSuitsArray = Object.keys(cardSuits)
const suit3 = cardSuitsArray.map((v)=> "3"+v) //["3club", "3diamond", "3hearts", "3spade"]
This post is licensed under CC BY 4.0 by the author.

React and Node backend authentication/authorization

IoT board customized