Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k 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 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...