如何在TypeScript中省略枚举中的一些项?

j2cgzkjk  于 2023-02-10  发布在  TypeScript
关注(0)|答案(3)|浏览(299)

我定义了一个枚举来澄清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 */;

如何定义表示Errcode中除Errcode.Ok之外的所有项的ErrorErrcode(并且它应该包括NotFoundError中的所有项)?
我不能定义更细粒度的类型,Union它们如下所示:

enum SuccessErrcode {
    Ok =0,
}
enum NotFoundErrcode {
    PostsNotFound=202,
    TagNotFound=203,
}
enum ErrorErrcode {
    Error=1,
}
type Errcode =SuccessErrcode|NotFoundError|SuccessErrcode;

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

vhmi4jdf

vhmi4jdf1#

从TypeScript 2.8开始,加上条件类型,您可以使用内置的Exclude来排除某些枚举值:

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 = Exclude<Errcode, Errcode.Ok>;

打字机Playground

sr4lhrrt

sr4lhrrt2#

首先定义更细粒度的类型,可能如下所示:

enum ErrorCode {
    Error = 1,
    AccessDeny = 201,
    PostsNotFound = 202,
    TagNotFound = 203,
}

enum SuccessCode {
    Ok = 0
}

然后,您可以将Union Type定义为SuccessCodeErrorCode

type ResultCode = ErrorCode | SuccessCode;

你可以这样使用它:

const myResult1: ResultCode = ErrorCode.AccessDeny;
const myResult2: ResultCode = SuccessCode.Ok;
0tdrvxhp

0tdrvxhp3#

这花了我相当多的时间才弄明白(你能告诉我我有多喜欢TS吗?)。我被Object.entries()从字典中产生数组的数组这一事实卡住了,我不得不把它转换回字典,这样我现有的代码就可以继续使用这两种类型。下面是我的解决方案(归功于Jake Holzinger的答案to this question):

enum Countries {
  UnitedStates = 'United States',
  Afghanistan = 'Afghanistan',
  Albania = 'Albania'}

const UsAndIslands = [
  Countries.UnitedStates];

const NonUsCountries = Object.entries(Countries)
  .filter((country) => !UsAndIslands.includes(country[1]))
  .reduce((dict, [key, value]) => Object.assign(dict, { [key]: value }), {});

console.log("Countries", Countries);
console.log("NonUsCountries", NonUsCountries);

试试看。

相关问题