0

I have:

export enum SiteCodes {
    'USA',
    'CAN',
    'GB'
}

export interface GetSkuItemsRequest {
    siteCode: SiteCodes;
}


export default class GetSkuItems {
    public event: APIGatewayProxyEvent;
    private PARAMS_TO_PICK = [
        'siteCode'
    ];

    private validateParams(pickedParams: { [key: string]: string }){
        const {
            siteCode
        } = pickedParams;

        if (!siteCode) {
            throw MISSING_PARAMS_ERROR;
        }

    }
}

What I want to do in the validateParams is to ensure that the siteCode in included in the enum of SiteCodes

Shamoon
  • 41,293
  • 91
  • 306
  • 570

2 Answers2

1

Since you can index into an enum with a string, my first pass at it was that you can verify it like this:

const isValid = SiteCodes[siteCode as any] !== undefined;

Live on the playground

There are a couple of problems with the above, though:

  1. It'll accept 0, 1, 2, "0", "1", and "2" as well as valid enum strings.

  2. It'll accept "valueOf", "toString", and other Object.prototype properties as valid enum strings.

So here's a more thorough version:

const isValid = !!(siteCode && isNaN(+siteCode) && Object.prototype.hasOwnProperty.call(SiteCodes, siteCode));

Live on the playground

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Thank you so much - so easy! – Shamoon Sep 18 '19 at 12:30
  • @Shamoon - Note: The first version of my answer would also accept `siteCode` being `0`, `1`, `2`, `"0"`, `"1"`, `"2"`, `"valueOf"`, and a few others as valid enum strings. I've updated with a more thorough version. – T.J. Crowder Sep 18 '19 at 13:31
1

You can use 'in' like:

enum SiteCodes {
    'USA',
    'CAN',
    'GB'
}

let badSiteCode = 'badSiteCode';
let validSiteCode = 'USA'

console.log(badSiteCode in SiteCodes);
console.log(validSiteCode in SiteCodes);

Checkout this fiddle: https://jsfiddle.net/dqLatzk2/

Tomasz Sikora
  • 1,649
  • 3
  • 19
  • 30
  • The only problem with this is that if you set `badSiteCode` to `0`, `1`, or `3`, you'll get a false positive, since the objects have properties both for the number version and the string version. ... ... ... which is also a problem with *my* answer. :-) – T.J. Crowder Sep 18 '19 at 13:21
  • Both of ours *also* accept `"valueOf"` and other `Object.prototype` properties. – T.J. Crowder Sep 18 '19 at 13:27