简体   繁体   中英

How to assign string types from a enum in Typescript?

So I have an enum which contains a set of strings

export enum apiErrors {
    INVALID_SHAPE = "INVALID_SHAPE",
    NOT_FOUND = "NOT_FOUND",
    EXISTS = "EXISTS",
    INVALID_AUTH = "INVALID_AUTH",
    INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR"
}

I defined an interface like below

export interface IApiResponse {
    status: boolean;
    payload: any;
    errorCode?: string; // I want this to be "INVALID_SHAPE" | "NOT_FOUND" and so on...
}

I know I can define just like "INVALID_SHAPE" | "NOT_FOUND" ... "INVALID_SHAPE" | "NOT_FOUND" ...

But is there a way to de-structure the enum to errorCode so that it can accept only one of those strings?

As @JBNizet and @AviadP mentioned, just set errorCode to the apiErrors enum. Typescript will automatically ensure that anything that implements the IApiResponse interface has errorCode set to be one of those values.

export enum apiErrors {
   INVALID_SHAPE = "INVALID_SHAPE",
   NOT_FOUND = "NOT_FOUND",
   EXISTS = "EXISTS",
   INVALID_AUTH = "INVALID_AUTH",
   INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR"
}

export interface IApiResponse {
   status: boolean;
   payload: any;
   errorCode?: apiErrors // this is the change
}

// this would now be invalid
const invalidResponse: IApiResponse = {
   status: false,
   payload: {foo: 'bar'},
   errorCode: 'something not in the enum',
};

// this is valid
const validResponse: IApiResponse = {
   status: false,
   payload: {foo: 'bar'},
   errorCode: apiErrors.INVALID_SHAPE,
};

// this is also valid
const anotherValidResponse: IApiResponse = {
   status: true,
   payload: {foo: 'bar'},
   // errorCode isn't included at all
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM