mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-26 01:19:11 +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', () => {
|
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();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
Reference in New Issue
Block a user