Skip to content

Commit

Permalink
Handle named function types specially in matchModuloWhitespace (#214)
Browse files Browse the repository at this point in the history
* repro for issue 213

* fix the bug
  • Loading branch information
danvk authored Nov 27, 2023
1 parent 5c1babe commit 22bb42d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
6 changes: 6 additions & 0 deletions src/test/ts-checker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,12 @@ describe('ts-checker', () => {
matchModuloWhitespace('BoundingBox | undefined', 'const box: BoundingBox | undefined'),
).toBe(false);
});

it('should normalize whitespace in function types', () => {
const actual = `function fetchANumber(input: RequestInfo | URL, init?: RequestInit | undefined): Promise<number>`;
const expected = `function fetchANumber( input: RequestInfo | URL, init?: RequestInit | undefined ): Promise<number>`;
expect(matchModuloWhitespace(actual, expected)).toBe(true);
});
});

describe('sortUnions', () => {
Expand Down
22 changes: 16 additions & 6 deletions src/ts-checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,18 +389,28 @@ export function matchModuloWhitespace(actual: string, expected: string): boolean
// TODO: it's much easier to normalize actual based on the displayParts
// This isn't 100% correct if a type has a space in it, e.g. type T = "string literal"
const normalize = (input: string) => {
const parts = input.split(/[:=]/, 2);
if (parts.length !== 2) {
// this might be a typo, e.g. missing the ":" or "=" in a type assertion.
return input;
const isFunction = !!input.match(/^ *function /);

let name: string;
let type: string;
if (!isFunction) {
const parts = input.split(/[:=]/, 2);
if (parts.length !== 2) {
// this might be a typo, e.g. missing the ":" or "=" in a type assertion.
return input;
}
[name, type] = parts;
} else {
name = 'n/a';
type = input;
}
const [name, type] = parts;

const normType = sortUnions(type)
.replace(/[\n\r ]+/g, ' ')
.replace(/\( */g, '(')
.replace(/ *\)/, ')')
.trim();
return `${name}: ${normType}`;
return isFunction ? normType : `${name}: ${normType}`;
};
const normActual = normalize(actual);
const normExpected = normalize(expected);
Expand Down

0 comments on commit 22bb42d

Please sign in to comment.