相关疑难解决方法(0)

TypeScript - 如何在TypeScript中省略Enum中的某些项?

我定义了一个Enum来阐明API请求状态:

const enum Errcode{
    Ok=0,
    Error=1,
    AccessDeny=201,
    PostsNotFound=202,
    TagNotFound=203,
    //...
}

type SuccessErrcode =Errcode.Ok;
type NotFoundError =Errcode.PostsNotFound|Errcode.TagNotFound;
type ErrorErrcode=/* there */;
Run Code Online (Sandbox Code Playgroud)

如何定义ErrorErrcode除了Errcode.Ok之外的所有Errcode项(它应该包括NotFoundError的所有项)?

我无法定义更细粒度的类型,Union他们喜欢这样:

enum SuccessErrcode {
    Ok =0,
}
enum NotFoundErrcode {
    PostsNotFound=202,
    TagNotFound=203,
}
enum ErrorErrcode {
    Error=1,
}
type Errcode =SuccessErrcode|NotFoundError|SuccessErrcode;
Run Code Online (Sandbox Code Playgroud)

如果我这样做,我将不能使用Errcode.xxx-使用的代码,我必须知道它在哪里被分配的(例如,从,Errcode.TagNotFoundNotFoundError.TagNotFound).并考虑到 - 当有TagErrcode和时NotFoundErrcode,TagNotFound=203将定义两次.

typescript

16
推荐指数
2
解决办法
2254
查看次数

枚举的枚举子集

假设我有以下enum类型:

public enum Country {
    CHINA,
    JAPAN,
    FRANCE,
    // ... and all other countries
    AUSTRIA,
    POLAND;
}
Run Code Online (Sandbox Code Playgroud)

现在我想创建这个枚举的子集,在概念上如下:

public enum EuropeanUnion constraints Country {
    FRANCE,
    // ... and all other countries within the European Union
    AUSTRIA,
    POLAND;
}

public enum LandlockedCountries constraints Country {
    // ... all landlocked countries
    AUSTRIA;
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个enum类型的子集,以便我可以编写诸如的方法

Set<Person> getNationalMembersOfEuropeanParliament(EuropeanUnion euCountry);
Run Code Online (Sandbox Code Playgroud)

使用EuropeanUnion参数的子类型可以euCountry防止API用户意外地传入无效的国家/地区,例如非欧盟国家/地区JAPAN.

有没有办法"约束"有效枚举值的范围,以便人们可以从静态类型系统中受益?

java

7
推荐指数
1
解决办法
1058
查看次数

标签 统计

java ×1

typescript ×1