console-app/lib/Types/TypeValidation.ts

45 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-05-09 19:51:43 +02:00
export class TypeValidation {
private readonly _general_type: string;
public get general_type (): string {
return this._general_type;
}
public get string_type (): 'string'|'number'|'boolean'|'array' {
return this._general_type as 'string'|'number'|'boolean'|'array';
}
public constructor (type: string) {
this._general_type = type;
}
public validate_type (value: unknown): boolean {
return typeof value === this.general_type;
}
public to_type (value: unknown): Promise<unknown> {
if (this.general_type === 'string')
return Promise.resolve (String (value));
if (this.general_type === 'number') {
const as_num = parseInt (String (value));
if (isNaN (as_num))
throw new Error ('value is not a number');
return Promise.resolve (as_num);
}
if (this.general_type === 'boolean') {
const as_num = parseInt (String (value));
if (
as_num !== 1 && as_num !== 0
&& !(/^(?:true|false)$/iu).test (String (value))
)
throw new Error ('value is not a boolean');
return Promise.resolve (
as_num === 1 || (/true/iu).test (String (value))
);
}
throw new Error ('unknown type');
}
}