ts-ref-kit
v1.1.20
Published
Type reflection and validation library for TypeScript
Readme
ts-ref-kit
TypeScript type reflection and validation library for runtime access and usage of TypeScript type information.
Features
- Type Reflection: Retrieve metadata for TypeScript classes, interfaces, type aliases, and enums at runtime
- Type Validation: Validate whether values conform to specific TypeScript type definitions
- JSON Conversion: Convert JSON strings to class instances
- Type Queries: Query inheritance relationships, interface implementations, and more between classes
- Generic Support: Support for reflection and validation of generic types
- Enum Handling: Access enum names, values, and type definitions
Installation
npm install ts-ref-kitQuick Start
Type Reflection Example
import { getClassDefinition, getInterfaceDefinition, getTypeAliasDefinition, getEnumDefinition } from 'ts-ref-kit';
// Get class definition
const classDef = getClassDefinition('MyClass');
console.log(classDef?.name); // Output: class name
console.log(classDef?.properties); // Output: class properties list
console.log(classDef?.methods); // Output: class methods list
// Get interface definition
const interfaceDef = getInterfaceDefinition('MyInterface');
console.log(interfaceDef?.name); // Output: interface name
console.log(interfaceDef?.properties); // Output: interface properties list
console.log(interfaceDef?.methods); // Output: interface methods list
// Get type alias definition
const typeAliasDef = getTypeAliasDefinition('MyTypeAlias');
console.log(typeAliasDef?.name); // Output: type alias name
console.log(typeAliasDef?.type); // Output: type definition
// Get enum definition
const enumDef = getEnumDefinition('MyEnum');
console.log(enumDef?.name); // Output: enum name
console.log(enumDef?.members); // Output: enum membersType Validation Example
import { isType, assertType } from 'ts-ref-kit';
// Validate if value matches type
const value = 'test';
const isString = isType(value, 'string');
console.log(isString); // Output: true
// Assert value matches type (throws error if not)
assertType<string>(value, 'string');
// Validate complex type
interface User {
name: string;
age: number;
}
const user = { name: 'John', age: 30 };
const isUser = isType(user, '{ name: string, age: number }');
console.log(isUser); // Output: trueJSON Conversion Example
import { JSONTransfer } from 'ts-ref-kit';
class User {
name: string;
age: number;
constructor() {
this.name = '';
this.age = 0;
}
}
const jsonString = '{"name":"John","age":30}';
const jsonTransfer = new JSONTransfer();
// Convert JSON string to class instance
const user = jsonTransfer.parse<User>(jsonString, User);
console.log(user instanceof User); // Output: true
console.log(user.name); // Output: John
console.log(user.age); // Output: 30Enum Operations Example
import { getEnumNames, getEnumValues } from 'ts-ref-kit';
enum Color {
Red,
Green,
Blue
}
// Get enum names list
const colorNames = getEnumNames('Color');
console.log(colorNames); // Output: ['Red', 'Green', 'Blue']
// Get enum values list
const colorValues = getEnumValues({ Color });
console.log(colorValues); // Output: [0, 1, 2]API Documentation
Core Type Definitions
- TypeDefinition: Core interface representing TypeScript types
- ClassDefinition: Definition for class types
- InterfaceDefinition: Definition for interface types
- TypeAliasDefinition: Definition for type aliases
- EnumDefinition: Definition for enum types
Type Reflection API
Class Related
getClassDefinition(arg: Constructor | object | string): ClassDefinition | undefinedgetClassByName(className: string): Constructor | undefined
Interface Related
getInterfaceDefinition(name: string): InterfaceDefinition | undefined
Type Alias Related
getTypeAliasDefinition(name: string, genericArgs?: TypeDefinition[]): TypeAliasDefinition | undefined
Enum Related
getEnumDefinition(name: string): EnumDefinition | undefinedgetEnumNames(enumName: string): string[]getEnumValues(args: { [enumName: string]: Record<string, string | number> }): (string | number)[]
Generic Type
getTypeDefinition(typeName: string, genericArgs?: TypeDefinition[]): TypeDefinition
Type Validation API
isType(value: unknown, type: Type | TypeDefinition, depth: number = 5): booleanassertType<T>(data: unknown, type: Type, depth: number = 5): TvalidateValue(value: unknown, typeDef: TypeDefinition, depth: number = 5): ValidateResult
JSON Conversion API
JSONTransferclassparse<T = unknown>(jsonString: JSONString<T>, type?: Type): T
Configuration Options
import { ReflectConfig } from 'ts-ref-kit';
ReflectConfig {
// Validation error handler
validationErrorHandler: function (e: ValidationError): void {
console.error(e.message);
console.error(e.failureResult?.errorStackFlow);
},
// Whether to enable validation
validation: true,
// Whether to enable debug mode
debug: false
}Advanced Usage
Generic Type Handling
import { getTypeDefinition } from 'ts-ref-kit';
// Get generic type definition
const arrayOfStringType = getTypeDefinition('Array<string>');
console.log(arrayOfStringType.arrayElementType?.name); // Output: string
// Use type literals
const mapType = getTypeDefinition('Map<string, number>');Type Relationship Queries
import { getClassDefinition, getInterfaceDefinition } from 'ts-ref-kit';
// Query if a class is a subclass of another class
const classDef = getClassDefinition('MyClass');
const isSubClass = classDef?.isSubClassOf('BaseClass');
// Query if a class is a superclass of another class
const isSuperClass = classDef?.isSuperClassOf('DerivedClass');Special Type Registration
import { registerSpecialType } from 'ts-ref-kit';
// Register custom special type
registerSpecialType('MySpecialType', (typeArgs) => {
return {
name: 'MySpecialType',
type: {
// Type definition
}
};
});Parser Configuration
The core functionality of ts-ref-kit relies on type metadata generated at compile time. The parser module provides integration capabilities with different build tools to extract type information and generate metadata during compilation.
Vite Plugin
In Vite projects, you can use reflectParserPlugin to automatically generate type metadata:
import { defineConfig } from 'vite'
import { reflectParserPlugin } from 'ts-ref-kit/parser'
export default defineConfig({
plugins: [
reflectParserPlugin({
entry: 'src/main.ts',
sourcePaths: 'src'
})
]
})Custom Build Configuration
If you're using other build tools or a custom build process, you can directly use reflectLoader:
import { reflectLoader } from 'ts-ref-kit/parser'
const loader = reflectLoader({
sourcePaths: 'src',
exclude: /node_modules/,
outputLog: true
})
// Transform a single file
const transformedCode = loader.transform(sourceCode, sourceFileName)
// Generate all metadata
const allMetas = loader.outputAllMetas()Parser Options
entry: Entry file path of the projectsourcePaths: Source code paths to process, can be a string or array of stringsexclude: File paths to exclude, can be a string, regular expression, or array of themforEnabledClassOnly: Whether to only process classes that implement theEnableReflectinterfaceoutputLog: Whether to output log information
Working Principle
- The parser scans TypeScript source code during compilation
- Extracts definitions of classes, interfaces, enums, and type aliases
- Generates type metadata and injects it into the compiled code
- Runtime access to this metadata is available through
ts-ref-kitAPIs
Node.js Environment Usage
In Node.js environments, you can directly use the parser to analyze TypeScript files:
const { reflectLoader } = require('ts-ref-kit/parser');
const fs = require('fs');
const sourceCode = fs.readFileSync('src/types.ts', 'utf8');
const loader = reflectLoader({
sourcePaths: 'src'
});
const transformedCode = loader.transform(sourceCode, 'src/types.ts');
const metadata = loader.outputAllMetas();
console.log(metadata);tsconfig.json Configuration
To enable decorator metadata generation, add the following configuration to your tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"plugins": [
{
"transform": "ts-ref-kit/parser"
}
]
}
}Webpack Configuration
In Webpack projects, you can configure through custom transformers:
const { ReflectParserPlugin } = require('ts-ref-kit/parser');
module.exports = {
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
options: {
getCustomTransformers: () => ({
before: [ReflectParserPlugin()]
})
}
}
]
}
]
}
};Development
Install Dependencies
npm installBuild Project
npm run buildRun Lint
npm run lintLicense
MIT
