如何在 TypeScript 中嵌套枚举?

Men*_*nas 3 enums typescript

假设我有一个像这样的函数,但枚举参数有更多可能的值:

enum API{
    userDetails = "/api/user/details",
    userPosts = "/api/user/posts",
    userComments = "/api/user/comments",
    postDetails = "/api/post/details",
    postComments = "/api/post/comments"
    //...
};

function callAPI(endpoint: API/*, some more params*/){
    // some code to deal with the specified endpoint...
}

callAPI(API.userComments);
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常,但我需要将枚举的许多值分组到一个有组织的层次结构中,以便使事情更有组织性......例如,如果调用 API 的语法可以是callAPI(API.user.comments)代替callAPI(API.userComments).

我尝试了类似下面的尝试,但看起来没有一个被接受为打字稿的有效语法。

尝试1

enum API{
    user = {
        details : "/api/user/details",
        userPorts : "/api/user/posts",
        userComments : "/api/user/comments"
    }
    post = {
        postDetails : "/api/post/details",
        postComments : "/api/post/comments"
    }
}
Run Code Online (Sandbox Code Playgroud)

尝试2

enum user {
    details = "/api/user/details",
    userPorts = "/api/user/posts",
    userComments = "/api/user/comments"
}
enum post {
    postDetails = "/api/post/details",
    postComments = "/api/post/comments"
}
enum API{
    user,
    post
}
Run Code Online (Sandbox Code Playgroud)

尝试3

enum user {
    details = "/api/user/details",
    userPorts = "/api/user/posts",
    userComments = "/api/user/comments"
}
enum post {
    postDetails = "/api/post/details",
    postComments = "/api/post/comments"
}
enum API{
    user = user,
    post = post
}
Run Code Online (Sandbox Code Playgroud)

尝试4

enum user {
    details = "/api/user/details",
    userPorts = "/api/user/posts",
    userComments = "/api/user/comments"
}
enum post {
    postDetails = "/api/post/details",
    postComments = "/api/post/comments"
}
enum API{
    user:user
    post:post
}
Run Code Online (Sandbox Code Playgroud)

A_A*_*A_A 8

您可以将其包装在名称空间内:

namespace API{
    export enum User {
        details = "/api/user/details",
        posts = "/api/user/posts",
        comments = "/api/user/comments",
    }
    export enum Post {
        details = "/api/post/details",
        comments = "/api/post/comments",
    }
}

console.log(API.User.comments)
console.log(API.Post.details)
Run Code Online (Sandbox Code Playgroud)