Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added support for Partial<T> #53

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 29 additions & 26 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const defaultFormat = "ts"
const defaultSuffix = "-ti";
// Default header prepended to the generated module.
const defaultHeader =
`/**
`/**
* This module was automatically generated by \`ts-interface-builder\`
*/
`;
Expand All @@ -28,23 +28,23 @@ export interface ICompilerOptions {
// The main public interface is `Compiler.compile`.
export class Compiler {
public static compile(
filePath: string,
options: ICompilerOptions = {},
): string {
const createProgramOptions = {target: ts.ScriptTarget.Latest, module: ts.ModuleKind.CommonJS};
filePath: string,
options: ICompilerOptions = {},
): string {
const createProgramOptions = { target: ts.ScriptTarget.Latest, module: ts.ModuleKind.CommonJS };
const program = ts.createProgram([filePath], createProgramOptions);
const checker = program.getTypeChecker();
const topNode = program.getSourceFile(filePath);
if (!topNode) {
throw new Error(`Can't process ${filePath}: ${collectDiagnostics(program)}`);
}
options = {format: defaultFormat, ignoreGenerics: false, ignoreIndexSignature: false, inlineImports: false, ...options}
options = { format: defaultFormat, ignoreGenerics: false, ignoreIndexSignature: false, inlineImports: false, ...options }
return new Compiler(checker, options, topNode).compileNode(topNode);
}

private exportedNames: string[] = [];

constructor(private checker: ts.TypeChecker, private options: ICompilerOptions, private topNode: ts.SourceFile) {}
constructor(private checker: ts.TypeChecker, private options: ICompilerOptions, private topNode: ts.SourceFile) { }

private getName(id: ts.Node): string {
const symbol = this.checker.getSymbolAtLocation(id);
Expand All @@ -54,6 +54,7 @@ export class Compiler {
private indent(content: string): string {
return content.replace(/\n/g, "\n ");
}

private compileNode(node: ts.Node): string {
switch (node.kind) {
case ts.SyntaxKind.Identifier: return this._compileIdentifier(node as ts.Identifier);
Expand Down Expand Up @@ -105,7 +106,7 @@ export class Compiler {
node.getText());
}

private compileOptType(typeNode: ts.Node|undefined): string {
private compileOptType(typeNode: ts.Node | undefined): string {
return typeNode ? this.compileNode(typeNode) : '"any"';
}

Expand Down Expand Up @@ -141,6 +142,8 @@ export class Compiler {
} else if (node.typeName.getText() === "Promise") {
// Unwrap Promises.
return this.compileNode(node.typeArguments[0]);
} else if (node.typeName.getText() === "Partial") {
return `t.partial(${this.compileNode(node.typeArguments[0])})`;
} else if (node.typeName.getText() === "Array") {
return `t.array(${this.compileNode(node.typeArguments[0])})`;
} else if (this.options.ignoreGenerics) {
Expand All @@ -156,7 +159,7 @@ export class Compiler {
}
private _compileTypeLiteralNode(node: ts.TypeLiteralNode): string {
const members = node.members
.map(n => this.compileNode(n))
.map(this.compileNode, this)
.filter(n => n !== ignoreNode)
.map(n => " " + this.indent(n) + ",\n");
return `t.iface([], {\n${members.join("")}})`;
Expand Down Expand Up @@ -198,7 +201,7 @@ export class Compiler {
private _compileInterfaceDeclaration(node: ts.InterfaceDeclaration): string {
const name = this.getName(node.name);
const members = node.members
.map(n => this.compileNode(n))
.map(this.compileNode, this)
.filter(n => n !== ignoreNode)
.map(n => " " + this.indent(n) + ",\n");
const extend: string[] = [];
Expand Down Expand Up @@ -252,8 +255,8 @@ export class Compiler {
"};\n"
}
const prefix = `import * as t from "ts-interface-checker";\n` +
(this.options.format === "ts" ? "// tslint:disable:object-literal-key-quotes\n" : "") +
"\n";
(this.options.format === "ts" ? "// tslint:disable:object-literal-key-quotes\n" : "") +
"\n";
return prefix +
this._compileSourceFileStatements(node) + "\n\n" +
"const exportedTypeSuite" + (this.options.format === "ts" ? ": t.ITypeSuite" : "") + " = {\n" +
Expand All @@ -273,8 +276,8 @@ export class Compiler {
}
private _formatExport(name: string, expression: string): string {
return this.options.format === "js:cjs"
? ` ${name}: ${this.indent(expression)},`
: `export const ${name} = ${expression};`;
? ` ${name}: ${this.indent(expression)}, `
: `export const ${name} = ${expression}; `;
}
}

Expand Down Expand Up @@ -309,23 +312,23 @@ function needsUpdate(srcPath: string, outPath: string): boolean {
*/
export function main() {
commander
.description("Create runtime validator module from TypeScript interfaces")
.usage("[options] <typescript-file...>")
.option("--format <format>", `Format to use for output; options are 'ts' (default), 'js:esm', 'js:cjs'`)
.option("-g, --ignore-generics", `Ignores generics`)
.option("-i, --ignore-index-signature", `Ignores index signature`)
.option("--inline-imports", `Traverses the full import tree and inlines all types into output`)
.option("-s, --suffix <suffix>", `Suffix to append to generated files (default ${defaultSuffix})`, defaultSuffix)
.option("-o, --outDir <path>", `Directory for output files; same as source file if omitted`)
.option("-v, --verbose", "Produce verbose output")
.option("-c, --changed-only", "Skip the build if the output file exists with a newer timestamp")
.parse(process.argv);
.description("Create runtime validator module from TypeScript interfaces")
.usage("[options] <typescript-file...>")
.option("--format <format>", `Format to use for output; options are 'ts' (default ), 'js:esm', 'js:cjs'`)
.option("-g, --ignore-generics", `Ignores generics`)
.option("-i, --ignore-index-signature", `Ignores index signature`)
.option("--inline-imports", `Traverses the full import tree and inlines all types into output`)
.option("-s, --suffix <suffix>", `Suffix to append to generated files (default ${defaultSuffix})`, defaultSuffix)
.option("-o, --outDir <path>", `Directory for output files; same as source file if omitted`)
.option("-v, --verbose", "Produce verbose output")
.option("-c, --changed-only", "Skip the build if the output file exists with a newer timestamp")
.parse(process.argv);

const files: string[] = commander.args;
const verbose: boolean = commander.verbose;
const changedOnly: boolean = commander.changedOnly;
const suffix: string = commander.suffix;
const outDir: string|undefined = commander.outDir;
const outDir: string | undefined = commander.outDir;
const options: ICompilerOptions = {
format: commander.format || defaultFormat,
ignoreGenerics: commander.ignoreGenerics,
Expand Down
2 changes: 1 addition & 1 deletion lib/macro/compileTypeSuite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export function compileTypeSuite(args: ICompilerArgs): string {
const context = `compiling file ${file} with options ${optionsString}`;
try {
compiled = Compiler.compile(file, options);
} catch (error) {
} catch (error: any) {
throw macroError(`Error ${context}: ${error.name}: ${error.message}`);
}
/*
Expand Down
Loading