Type reflection and validation library for TypeScript
npm install ts-ref-kitTypeScript type reflection and validation library for runtime access and usage of TypeScript type information.
- 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
``bash`
npm install ts-ref-kit
`typescript
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 members
`
`typescript
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
// 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: true
`
`typescript
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
console.log(user instanceof User); // Output: true
console.log(user.name); // Output: John
console.log(user.age); // Output: 30
`
`typescript
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]
`
- 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
#### 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
-
#### Generic Type
- getTypeDefinition(typeName: string, genericArgs?: TypeDefinition[]): TypeDefinition
- isType(value: unknown, type: Type | TypeDefinition, depth: number = 5): booleanassertType
- validateValue(value: unknown, typeDef: TypeDefinition, depth: number = 5): ValidateResult
-
- JSONTransfer classparse
-
`typescript
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
}
`
`typescript
import { getTypeDefinition } from 'ts-ref-kit';
// Get generic type definition
const arrayOfStringType = getTypeDefinition('Array
console.log(arrayOfStringType.arrayElementType?.name); // Output: string
// Use type literals
const mapType = getTypeDefinition('Map
`
`typescript
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');
`
`typescript
import { registerSpecialType } from 'ts-ref-kit';
// Register custom special type
registerSpecialType('MySpecialType', (typeArgs) => {
return {
name: 'MySpecialType',
type: {
// Type definition
}
};
});
`
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.
In Vite projects, you can use reflectParserPlugin to automatically generate type metadata:
`typescript
import { defineConfig } from 'vite'
import { reflectParserPlugin } from 'ts-ref-kit/parser'
export default defineConfig({
plugins: [
reflectParserPlugin({
entry: 'src/main.ts',
sourcePaths: 'src'
})
]
})
`
If you're using other build tools or a custom build process, you can directly use reflectLoader:
`typescript
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()
`
- 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 the EnableReflect interfaceoutputLog
- : Whether to output log information
1. The parser scans TypeScript source code during compilation
2. Extracts definitions of classes, interfaces, enums, and type aliases
3. Generates type metadata and injects it into the compiled code
4. Runtime access to this metadata is available through ts-ref-kit APIs
In Node.js environments, you can directly use the parser to analyze TypeScript files:
`javascript
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);
`
To enable decorator metadata generation, add the following configuration to your tsconfig.json:
`json`
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"plugins": [
{
"transform": "ts-ref-kit/parser"
}
]
}
}
In Webpack projects, you can configure through custom transformers:
`javascript
const { ReflectParserPlugin } = require('ts-ref-kit/parser');
module.exports = {
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
options: {
getCustomTransformers: () => ({
before: [ReflectParserPlugin()]
})
}
}
]
}
]
}
};
`
`bash`
npm install
`bash`
npm run build
`bash``
npm run lint
MIT