Skip to content

Instantly share code, notes, and snippets.

@iShawnWang
Created November 25, 2019 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iShawnWang/5723ae24d64467837e6d54805316c23b to your computer and use it in GitHub Desktop.
Save iShawnWang/5723ae24d64467837e6d54805316c23b to your computer and use it in GitHub Desktop.
Typescript 枚举 扩展
interface Enum {
[id: number]: string
}
const getEnumKeys = (e: Enum) => {
return Object.keys(e)
.map(key => e[key])
.filter(value => typeof value === 'string') as string[]
}
enum TrafficLight {
red = 1,
green = 2,
yellow = 3,
}
namespace TrafficLight {
export function keys() {
return getEnumKeys(TrafficLight)
}
export function parse(light: Number): TrafficLight {
return <TrafficLight>light
}
export function desc(light: TrafficLight) {
switch (light) {
case TrafficLight.green:
return '绿灯'
case TrafficLight.red:
return '红灯'
case TrafficLight.yellow:
return '黄灯'
default:
return ''
// 或者 throw new Error("参数错误")
}
}
}
console.error('emmmmmm')
console.log(TrafficLight.keys())
console.log(TrafficLight.desc(2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment