Fix coerce enum (#1064)

This commit is contained in:
Alex Christoffer Rasmussen
2024-06-11 13:03:34 +02:00
committed by GitHub
parent 13c49f3652
commit 657aed1244
2 changed files with 6 additions and 6 deletions
@@ -22,18 +22,18 @@ describe('parses a colour string that is', () => {
describe('match a string to an enum that is', () => { describe('match a string to an enum that is', () => {
enum testEnum { enum testEnum {
'abc', ABC = 'abc',
'def', DEF = 'def',
'ghi', GHI = 'ghi',
} }
it('valid key', () => { it('valid key', () => {
const key = coerceEnum<testEnum>('abc', testEnum); const key = coerceEnum<testEnum>('abc', testEnum);
expect(key).toBe('abc'); expect(key).toBe('abc');
}); });
it('invalid key', () => { it('invalid key', () => {
expect(() => coerceEnum('123', testEnum)).toThrowError(Error('Invalid value received')); expect(() => coerceEnum('123', testEnum)).toThrow();
}); });
it('invalid type', () => { it('invalid type', () => {
expect(() => coerceEnum(123, testEnum)).toThrowError(Error('Invalid value received')); expect(() => coerceEnum(123, testEnum)).toThrow();
}); });
}); });
+1 -1
View File
@@ -7,7 +7,7 @@ import { isColourHex } from 'ontime-utils';
* @throws {Error} Throws an error value is not found in the enum. * @throws {Error} Throws an error value is not found in the enum.
*/ */
export function coerceEnum<T>(value: unknown, list: object): T { export function coerceEnum<T>(value: unknown, list: object): T {
if (typeof value !== 'string' || !(value in list)) { if (typeof value !== 'string' || !Object.values(list).includes(value)) {
throw new Error('Invalid value received'); throw new Error('Invalid value received');
} }
return value as T; return value as T;