V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
imherer
V2EX  ›  程序员

ts 里类似 golang 这种写法怎么实现?

  •  
  •   imherer · 52 天前 · 2609 次点击
    这是一个创建于 52 天前的主题,其中的信息可能已经有所发展或是发生改变。

    假如我现在有一个status,它的值是数字,但是需要有一个中文的说明,于是在 golang 里可以这样写

    go:
    type Status int
    
    const Success Status = 1
    const Failed Status = 2
    
    func (s Success) ToString() string{
    	return "成功"
    }
    func (s Failed) ToString() string{
    	return "失败"
    }
    

    在使用的时候,如果我想要字符串的说明直接 Success.ToString()就行了

    ts 里有类似的实现吗?

    我现在是这样写的

    ts:
    export enum Status {
      Success = { id: 1, value: "成功" },
      Failed = { id: 2, value: "失败" },
    }
    

    使用:Status.Success.value

    22 条回复    2024-07-17 14:19:20 +08:00
    yukinomiu
        1
    yukinomiu  
       52 天前
    你确定 golang 可以这么写?
    sunny352787
        2
    sunny352787  
       52 天前
    别瞎说啊,golang 不是这么写的
    imherer
        3
    imherer  
    OP
       52 天前
    @yukinomiu
    @sunny352787
    不好意思,确实是写错了,应该是把 Success 和 Failed 分别定义 type
    Vegetable
        4
    Vegetable  
       52 天前
    你这 golang 的代码根本不对,实际上写法会比这个丑很多,因为你没办法为值编写方法,你只能为类型编写方法。
    写出来大概就是:



    type Status int

    const Success Status = 1
    const Failed Status = 2

    func (s Status) ToString() string {
    if s == Failed {
    return "失败"
    }
    if s == Success {
    return "成功"
    }
    return "成功"
    }

    这样值和类型方法耦合,我觉得相当难看,ts 想做成这样单独定义一个 explain(value)也没啥区别吧
    pangdundun996
        5
    pangdundun996  
       52 天前
    ```go
    type Status int
    const Success Status = 1
    const Failed Status = 2
    func (s Status) ToString() string {
    if s == Success {
    return "success"
    }
    return "failed"
    }
    ```
    方法只能绑到 type 上吧
    LuckyLauncher
        6
    LuckyLauncher  
       52 天前
    你是不是混淆了类型和值的概念
    enchilada2020
        7
    enchilada2020  
       52 天前 via Android
    enum Status {
    Success = 1,
    Failed
    }

    console.log(Status.Success)
    console.log(Status[Status.Success])

    建议翻翻文档 Reverse Mappings 那节 清清楚楚写着呢
    kriszu
        8
    kriszu  
       52 天前
    你要在 ts 里实现这种效果,没必要用枚举啊,枚举的值只能是 string,number,boolean ,你可以定义一个对象或者类来实现
    horizon
        9
    horizon  
       52 天前
    自定义 enum class ,然后自己实现 toString 方法
    另外,ts 里不建议用自带的 enum
    https://mkosir.github.io/typescript-style-guide/#enums--const-assertion
    sunny352787
        10
    sunny352787  
       52 天前
    @Vegetable 丑点无所谓,反正都是 stringer 生成
    DiamondYuan
        11
    DiamondYuan  
       52 天前 via Android
    class Status {
    construtor ( private value:number ,private label:string )


    toString (){
    return this.label


    valueOf (){
    return this.value






    const success = new Status ( 1 ,“成功”)
    imherer
        12
    imherer  
    OP
       52 天前
    @enchilada2020 原来可以这样,不过我想要中文说明的话 key 定义成中文感觉有点怪怪的
    imherer
        13
    imherer  
    OP
       52 天前
    Morriaty
        14
    Morriaty  
       52 天前
    你需要比较枚举值吗?不需要的话,直接用 string 定义枚举啊
    imherer
        15
    imherer  
    OP
       52 天前
    @Morriaty 需要比较的。 主要是 string 是中文,枚举定义成中文感觉有点怪怪的
    wpzz
        16
    wpzz  
       52 天前
    不能这么写,状态 KeyVal ,和状态定义需要解耦。
    FanGanXS
        17
    FanGanXS  
       52 天前   ❤️ 1
    ```go
    var StatusMap = map[Status]string{
    Success: "成功",
    Failed: "失败",
    }

    type Status int

    const (
    Success Status = iota
    Failed
    )

    func (s Status) ToString() string {
    return StatusMap[s]
    }

    golang 的写法应该是这样,用 map 来映射 status 和字符串就好了。
    这样写的时候只需要关注 map 而不需要关注 ToString 的实现。
    lovedebug
        18
    lovedebug  
       52 天前   ❤️ 1
    GPT 给的写法

    enum Status {
    Success = 1,
    Failed = 2,
    }

    const StatusMessages = {
    [Status.Success]: "成功",
    [Status.Failed]: "失败",
    };

    function getStatusMessage(status: Status): string {
    return StatusMessages[status];
    }

    // 使用示例
    console.log(getStatusMessage(Status.Success)); // 输出: 成功
    console.log(getStatusMessage(Status.Failed)); // 输出: 失败
    lisongeee
        19
    lisongeee  
       52 天前
    export const Success = { id: 1, value: '成功' } as const;
    export const Failed = { id: 2, value: '失败' } as const;
    export type Status = typeof Success | typeof Failed;
    supuwoerc
        20
    supuwoerc  
       52 天前
    export enum RoomTypes {
    OR = "手术室",
    SVG = "抢救室",
    }

    export const RoomTypeOptions = [
    {
    key: RoomTypes[RoomTypes.OR],
    value: 1,
    label: RoomTypes.OR,
    },
    {
    key: RoomTypes[RoomTypes.SVG],
    value: 2,
    label: RoomTypes.SVG,
    },
    ];

    // --------------------------------

    export const ROOM_OPTIONS = {
    OR: {
    key: "OR",
    value: 1,
    label: "手术室",
    },
    SVG: {
    key: "SVG",
    value: 2,
    label: "急救室",
    },
    } as const;

    export type RoomTypeKey = keyof typeof ROOM_OPTIONS;

    export type RoomType = (typeof ROOM_OPTIONS)[RoomTypeKey];
    lysShub
        21
    lysShub  
       52 天前   ❤️ 1
    go 是这样写的

    //go:generate stringer -linecomment -output status_gen.go -type=Status
    type Status int

    const (
    _ Status = iota
    Success // 成功
    Failed // 失败
    )
    Leonkennedy2
        22
    Leonkennedy2  
       52 天前
    我问了一下克劳德

    在 TypeScript 中,您可以通过几种方式来实现类似 Golang 的功能。以下是一些可能的方法:

    1. 使用枚举和命名空间结合:

    ```typescript
    enum StatusEnum {
    Success = 1,
    Failed = 2
    }

    namespace Status {
    export const Success = StatusEnum.Success;
    export const Failed = StatusEnum.Failed;

    export function toString(status: StatusEnum): string {
    switch (status) {
    case StatusEnum.Success:
    return "成功";
    case StatusEnum.Failed:
    return "失败";
    default:
    return "未知";
    }
    }
    }

    // 使用
    console.log(Status.toString(Status.Success)); // 输出:成功
    ```

    2. 使用类和静态方法:

    ```typescript
    class Status {
    static readonly Success = new Status(1, "成功");
    static readonly Failed = new Status(2, "失败");

    private constructor(public readonly id: number, public readonly value: string) {}

    toString(): string {
    return this.value;
    }
    }

    // 使用
    console.log(Status.Success.toString()); // 输出:成功
    console.log(Status.Failed.value); // 输出:失败
    ```

    3. 使用对象和函数:

    ```typescript
    const Status = {
    Success: 1,
    Failed: 2,
    toString(status: number): string {
    switch (status) {
    case Status.Success:
    return "成功";
    case Status.Failed:
    return "失败";
    default:
    return "未知";
    }
    }
    } as const;

    // 使用
    console.log(Status.toString(Status.Success)); // 输出:成功
    ```

    4. 使用 Symbol 和对象:

    ```typescript
    const Status = {
    Success: Symbol('Success'),
    Failed: Symbol('Failed'),
    toString(status: symbol): string {
    switch (status) {
    case Status.Success:
    return "成功";
    case Status.Failed:
    return "失败";
    default:
    return "未知";
    }
    }
    };

    // 使用
    console.log(Status.toString(Status.Success)); // 输出:成功
    ```

    这些方法中,第 2 种(使用类和静态方法)可能最接近您的 Golang 示例。它允许您使用`Status.Success.toString()`来获取字符串描述,同时保持了类型安全性。

    选择哪种方法取决于您的具体需求和偏好。每种方法都有其优点和适用场景。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1155 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 23:48 · PVG 07:48 · LAX 16:48 · JFK 19:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.