Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

TypeScript中,联合类型可以取代枚举么?

TypeScript中的联合类型,可以联合各种基础类型和组合类型,比如:

type Direction = 'top' | 'left' | 'bottom' | 'right';
type code = 200 | 201 | 202 | 203 | 403 | 404 | 500;
type sex = 'male' | 'female';

这样看来联合类型和枚举的表现和用法都很相似,那么可不可以使用联合类型取代枚举呢

比如下面的案例

type code = '200' | '203' | '204' | '403' | '404';
const res: {code: ocde} = {code: "203"};

switch (res.code){
    case "202": break;
    case "203": break;
    case "204": break;
    case "403": break;
    case "404": break;
    default: break;

这样的用法和枚举差不多,在编辑器中也有智能提示和自动补全


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

完全可以的
枚举适合用在你想解释这些值的场景下,这样用起来就更加语义化


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...