Created
November 25, 2019 01:57
-
-
Save iShawnWang/5723ae24d64467837e6d54805316c23b to your computer and use it in GitHub Desktop.
Typescript 枚举 扩展
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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