library-ts/browser/tools/TypeUtilities.ts

162 lines
2.4 KiB
TypeScript

export type NullType = "null";
export type UndefinedType = "undefined";
export type PrimitiveType = "string" | "boolean" | "number";
export type DataType = PrimitiveType | NullType | UndefinedType | "object" ;
export type Action<T> = (t:T)=>void;
export type Predicate<T> = (t:T)=>boolean;
export type Func<R> = ()=>R;
export type Func1<I1,R> = ( i1:I1 ) => R;
export type Func2<I1,I2,R> = ( i1:I1, i2:I2 ) => R;
export type Func3<I1,I2,I3,R> = ( i1:I1, i2:I2, i3:I3 ) => R;
export interface ClassConstructor
{
prototype:PrototypeFunction
}
export interface PrototypeFunction
{
isPrototypeOf:( value:any ) => boolean;
}
export interface ObjectType
{
constructor:ClassConstructor;
}
export function isClassOf( value:any, classType:ClassConstructor )
{
return classType.prototype.isPrototypeOf( value );
}
export function castClass<T>( value:any, classType:ClassConstructor, alternativeValue:T = null )
{
if ( isClassOf( value, classType ) )
{
return value as T;
}
return alternativeValue;
}
export function getClass( value:any ):ClassConstructor
{
if ( isPrimitive( value ) )
{
return null;
}
if ( isNoValue( value ) )
{
return null;
}
return value.constructor;
}
export function hasOwnProp( value:any, name:string )
{
if ( ! value )
{
return false;
}
return Object.prototype.hasOwnProperty.call( value, name );
}
export function isNoValue( value:any )
{
if ( value === null )
{
return true;
}
if ( value === undefined )
{
return true;
}
return false;
}
export function isFunction( value:any )
{
if ( isNoValue( value ) )
{
return false;
}
if ( "function" === typeof( value ) )
{
return true;
}
return false;
}
export function getMemberName( parent:any, member:any )
{
for ( let it in parent )
{
if ( parent[ it ] === member )
{
return it;
}
}
return null;
}
export function isPrimitive( value:any )
{
if ( isNoValue( value ) )
{
return false;
}
let type = typeof( value );
if ( "string" === type )
{
return true;
}
if ( "number" === type )
{
return true;
}
if ( "boolean" === type )
{
return true;
}
return false;
}
export function className( value:any )
{
if ( value === null )
{
return "null";
}
if ( value === undefined )
{
return "undefined";
}
let type = typeof value;
if ( type === "object" )
{
return value.constructor.name;
}
return type;
}