mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-09 01:13:55 +00:00
Fix coerce enum (#1064)
This commit is contained in:
committed by
GitHub
parent
13c49f3652
commit
657aed1244
@@ -22,18 +22,18 @@ describe('parses a colour string that is', () => {
|
||||
|
||||
describe('match a string to an enum that is', () => {
|
||||
enum testEnum {
|
||||
'abc',
|
||||
'def',
|
||||
'ghi',
|
||||
ABC = 'abc',
|
||||
DEF = 'def',
|
||||
GHI = 'ghi',
|
||||
}
|
||||
it('valid key', () => {
|
||||
const key = coerceEnum<testEnum>('abc', testEnum);
|
||||
expect(key).toBe('abc');
|
||||
});
|
||||
it('invalid key', () => {
|
||||
expect(() => coerceEnum('123', testEnum)).toThrowError(Error('Invalid value received'));
|
||||
expect(() => coerceEnum('123', testEnum)).toThrow();
|
||||
});
|
||||
it('invalid type', () => {
|
||||
expect(() => coerceEnum(123, testEnum)).toThrowError(Error('Invalid value received'));
|
||||
expect(() => coerceEnum(123, testEnum)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import { isColourHex } from 'ontime-utils';
|
||||
* @throws {Error} Throws an error value is not found in the enum.
|
||||
*/
|
||||
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');
|
||||
}
|
||||
return value as T;
|
||||
|
||||
Reference in New Issue
Block a user