Skip to content

Commit

Permalink
feat: make types importable in createDts()
Browse files Browse the repository at this point in the history
  • Loading branch information
Gumball12 committed Feb 25, 2024
1 parent 5689657 commit 116e9a7
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 14 deletions.
34 changes: 27 additions & 7 deletions src/__tests__/core.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { describe, it, expect } from 'vitest';
import { createDts } from '../core/createDts';

const PREFIX = `// Generated by generate-dts
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols`;

describe('createDts', () => {
it('Common forms', () => {
const name = 'createDts';
Expand Down Expand Up @@ -43,19 +49,33 @@ describe('createDts', () => {

expect(dts).toBe(getDtsBody(name, ['a: string', 'b: unknown']));
});
});

const PREFIX = `// Generated by generate-dts
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
it('With imports', () => {
const name = 'createDts';
const dts = createDts(
name,
{ a: 'A' },
{ importTypes: [{ name: 'A', from: './a' }] },
);

expect(dts).toBe(
`${PREFIX}
import { A } from './a';
export {}
declare global {`;
declare global {
export interface ${name} {
a: A
}
}`,
);
});
});

const getDtsBody = (name: string, fieldList: string[]) => {
const body = fieldList.map(field => ` ${field}`).join('\n');
return `${PREFIX}
export {}
declare global {
export interface ${name} {
${body}
}
Expand Down
33 changes: 26 additions & 7 deletions src/core/createDts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,46 @@ const IGNORES = [

export type CreateDtsOptions = Partial<{
defaultType: string;
importTypes: Import[];
}>;

type Import = { name: string; from: string };

export const createDts = (
name: string,
object: object,
options = {} as CreateDtsOptions,
) => {
): string => {
const body = createItem(object, 4, defaultOptions(options));
const imports = createImport(options.importTypes || []);

return `${INFO}
${IGNORES}
export {}
declare global {
export interface ${name} ${body}
}`;
const result = [
INFO,
IGNORES,
imports,
'export {}',
'declare global {',
` export interface ${name} ${body}`,
'}',
]
.filter(v => v)
.join('\n');

return result;
};

const defaultOptions = (options: CreateDtsOptions) => ({
defaultType: options.defaultType || 'any',
});

const createImport = (imports: Import[]) => {
if (!imports.length) {
return;
}

return imports.map(i => `import { ${i.name} } from '${i.from}';`).join('\n');
};

const createItem = <T>(
object: T,
space: number,
Expand Down

0 comments on commit 116e9a7

Please sign in to comment.