enum Movement { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT" } function handlePlayerInput(key: string) { switch (key) { case Movement.Up: // 移动玩家角色向上 console.log("移动玩家角色向上"); break; case Movement.Down: // 移动玩家角色向下 console.log("移动玩家角色向下"); break; case Movement.Left: // 移动玩家角色向左 console.log("移动玩家角色向左"); break; case Movement.Right: // 移动玩家角色向右 console.log("移动玩家角色向右"); break; default: console.log("无效的输入"); } }在这个例子中,我们定义了一个名为 Movement 的枚举,它包含四个成员,分别代表四个方向:上、下、左、右。然后,我们使用这个枚举在 handlePlayerInput 函数中处理玩家的输入。
enum StatusCode { OK = 200, BadRequest = 400, NotFound = 404 } function handleResponse(code: StatusCode): string { if (code === StatusCode.OK) { return "请求成功"; } else if (code === StatusCode.NotFound) { return "资源未找到"; } else if (code === StatusCode.BadRequest) { return "错误请求"; } else { return "未知响应码"; } } // 假设我们有几个不同的响应码 const responseCode1 = 200; const responseCode2 = 404; const responseCode3 = 400; // 堆代码 duidaima.com // 将数字转换为StatusCode类型,并调用handleResponse函数 console.log(handleResponse(responseCode1 as StatusCode)); // 输出:请求成功 console.log(handleResponse(responseCode2 as StatusCode)); // 输出:资源未找到 console.log(handleResponse(responseCode3 as StatusCode)); // 输出:错误请求在这个例子中,我们定义了一个名为 StatusCode 的枚举,它包含三个成员,分别代表 HTTP 状态码:200(OK),400(BadRequest),404(NotFound)。然后,我们在 handleResponse 函数中使用这个枚举来处理不同的 HTTP 响应码。
enum PayloadActionLoadingState { Idle = "idle", Loading = "loading", Failed = "failed", Success = "success" }这个枚举定义了异步操作的不同状态,如“空闲”(Idle)、“加载中”(Loading)、“失败”(Failed)和“成功”(Success)。在 Redux Toolkit 中,管理这些状态非常常见。
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; interface DataState { data: any; loadingState: PayloadActionLoadingState; error: string | null; } const initialState: DataState = { data: null, loadingState: PayloadActionLoadingState.Idle, error: null, }; const dataSlice = createSlice({ name: 'data', initialState, reducers: { fetchDataStart(state) { state.loadingState = PayloadActionLoadingState.Loading; state.error = null; }, fetchDataSuccess(state, action: PayloadAction<any>) { state.loadingState = PayloadActionLoadingState.Success; state.data = action.payload; }, fetchDataFailed(state, action: PayloadAction<string>) { state.loadingState = PayloadActionLoadingState.Failed; state.error = action.payload; }, }, }); export const { fetchDataStart, fetchDataSuccess, fetchDataFailed } = dataSlice.actions; export default dataSlice.reducer;使用 Slice 和 枚举
import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { fetchDataStart, fetchDataSuccess, fetchDataFailed } from './dataSlice'; import { RootState } from './store'; import { PayloadActionLoadingState } from './payloadActionLoadingState'; const DataComponent: React.FC = () => { const dispatch = useDispatch(); const { data, loadingState, error } = useSelector((state: RootState) => state.data); useEffect(() => { const fetchData = async () => { dispatch(fetchDataStart()); try { const response = await fetch('https://api.example.com/data'); const result = await response.json(); dispatch(fetchDataSuccess(result)); } catch (err) { dispatch(fetchDataFailed(err.toString())); } }; fetchData(); }, [dispatch]); if (loadingState === PayloadActionLoadingState.Loading) { return <div>Loading...</div>; } if (loadingState === PayloadActionLoadingState.Failed) { return <div>Error: {error}</div>; } if (loadingState === PayloadActionLoadingState.Success) { return <div>Data: {JSON.stringify(data)}</div>; } return <div>Idle</div>; }; export default DataComponent;解释
PayloadActionLoadingState 枚举定义了异步操作的四种状态。
使用 createSlice 创建了一个名为 data 的 slice,包含初始状态和 reducers。
fetchDataFailed:设置 loadingState 为 Failed,并存储错误信息。
enum ShapeType { Circle = "Circle", Rectangle = "Rectangle" } interface Shape { type: ShapeType; } interface Circle extends Shape { type: ShapeType.Circle; radius: number; } interface Rectangle extends Shape { type: ShapeType.Rectangle; width: number; height: number; } function calculateArea(shape: Shape): number { switch (shape.type) { case ShapeType.Circle: const circle = shape as Circle; // 类型断言为 Circle return Math.PI * circle.radius * circle.radius; case ShapeType.Rectangle: const rectangle = shape as Rectangle; // 类型断言为 Rectangle return rectangle.width * rectangle.height; default: throw new Error("Invalid shape type"); } }具体的形状接口(Circle, Rectangle)扩展了基础的 Shape 接口,并且必须将其 type 属性设置为对应的枚举值。我们可以创建一些形状实例,并使用 calculateArea 函数来计算它们的面积:
const myCircle: Circle = { type: ShapeType.Circle, radius: 5 }; const myRectangle: Rectangle = { type: ShapeType.Rectangle, width: 10, height: 5 }; console.log(`Circle Area: ${calculateArea(myCircle)}`); // 输出:Circle Area: 78.53981633974483 console.log(`Rectangle Area: ${calculateArea(myRectangle)}`); // 输出:Rectangle Area: 50代码解释
ShapeType 枚举包含两个成员:Circle 和 Rectangle,表示两种形状类型。
Shape 接口有一个 type 属性,类型为 ShapeType 枚举。
Rectangle 接口扩展了 Shape,并添加了 width 和 height 属性,同时将 type 属性固定为 ShapeType.Rectangle。
enum Suit { Hearts = "♥", // 红色花色 Diamonds = "♦", // 红色花色 Clubs = "♣", // 黑色花色 Spades = "♠" // 黑色花色 } enum Rank { Ace = 1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } function getCardValue(rank: Rank): number { if (rank <= Rank.Ten) { return rank; } else { return 10; } } interface Card { suit: Suit; rank: Rank; color: string; // 根据花色派生的属性 } function createCard(suit: Suit, rank: Rank): Card { return { suit, rank, color: suit === Suit.Hearts || suit === Suit.Diamonds ? 'Red' : 'Black' } } // 使用示例 let card1 = createCard(Suit.Hearts, Rank.Ace); console.log(`The Ace of Hearts is red: ${card1.color}`); // 输出:The Ace of Hearts is red: Red let card2 = createCard(Suit.Spades, Rank.Queen); console.log(`The Queen of Spades is black: ${card2.color}`); // 输出:The Queen of Spades is black: Black解释
Rank 枚举定义了扑克牌的等级,从 Ace 到 King。
getCardValue 函数接受一个 Rank 类型的参数,并返回该牌的数值。对于 Ace 到 Ten,它们的数值等于等级本身。对于 Jack、Queen 和 King,它们的数值为 10。
Card 接口描述了一张牌的结构,包括花色、等级和颜色属性。颜色属性是根据花色派生的,红色花色(Hearts 和 Diamonds)为红色,黑色花色(Clubs 和 Spades)为黑色。
createCard 函数接受花色和等级作为参数,并返回一个 Card 对象。该函数根据花色来设置颜色属性。