Skip to content
Closed
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Fixes

- In TypeScript, an arrow function assigned to a `const` written with a function type, like `const onChange: OnChange = (scene) => …`, now gives its parameters the types that function type declares, and a destructured parameter's properties too when the function type writes their object type in place, as in `(props: { scene: Scene }) => void`; a method call on them links to the right class instead of one picked by name. Re-index TypeScript projects after upgrading (#3443).

## [1.6.5] - 2026-11-28

Expand Down
345 changes: 345 additions & 0 deletions __tests__/ts-callback-typed-arrow.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,345 @@
/**
* An arrow assigned to a `const` written with a function type gets its
* parameters' types from that type, as the TypeScript checker gives them
* (#3443): `const f: OnScene = (scene) => …` with `type OnScene = (scene:
* Scene) => void`, and a destructured `({ scene, value }) => …` with `type
* OnChange = (props: { scene: Scene; value: number }) => void`. A method call
* on such a parameter links the declared type's method, not one picked by
* name. On excalidraw, `const handleDegreeChange: DragInputCallbackType<…> =
* ({ scene, … }) => { scene.mutateElement(…) }` went to `App.mutateElement`.
*/
import { describe, it, expect, afterAll } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { CodeGraph } from '../src';

const roots: string[] = [];
afterAll(() => {
for (const r of roots.splice(0)) fs.rmSync(r, { recursive: true, force: true });
});

function write(root: string, files: Record<string, string>): void {
for (const [rel, content] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
fs.writeFileSync(path.join(root, rel), content);
}
}

async function indexed(files: Record<string, string>): Promise<{ cg: CodeGraph; root: string }> {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-ts-cb-arrow-'));
roots.push(root);
write(root, files);
return { cg: await CodeGraph.init(root, { index: true }), root };
}

/** `function -> file:Owner::method` for every calls edge out of the file. */
function callsFrom(cg: CodeGraph, file: string): string[] {
const out: string[] = [];
for (const n of cg.getNodesInFile(file)) {
for (const e of cg.getOutgoingEdgesFrom([n.id], ['calls'])) {
const t = cg.getNode(e.target);
out.push(`${n.name} -> ${t ? `${path.basename(t.filePath)}:${t.qualifiedName}` : '?'}`);
}
}
return out.sort();
}

const SCENE_TS = `export class Scene {
mutateElement(id: number): number { return id; }
}
`;
const APP_TSX = `export class App {
mutateElement(id: number): number { return -id; }
}
`;

describe('#3443: an arrow typed by the function type of its const', () => {
it('the issue repro: a plain and a destructured parameter', async () => {
const { cg } = await indexed({
'src/scene.ts': SCENE_TS,
'src/app.tsx': APP_TSX,
'src/types.ts': `import type { Scene } from './scene';
export type OnChange = (props: { scene: Scene; value: number }) => void;
export type OnScene = (scene: Scene) => void;
`,
'src/angle.tsx': `import type { Scene } from './scene';
import type { OnChange, OnScene } from './types';

export const destructured: OnChange = ({ scene, value }) => {
scene.mutateElement(value);
};

export const plain: OnScene = (scene) => {
scene.mutateElement(1);
};

export const lone: OnScene = scene => scene.mutateElement(2);

export const annotated = ({ scene, value }: { scene: Scene; value: number }) => {
scene.mutateElement(value);
};
`,
});
try {
const calls = callsFrom(cg, 'src/angle.tsx');
for (const fn of ['destructured', 'plain', 'lone', 'annotated']) {
expect(calls).toContain(`${fn} -> scene.ts:Scene::mutateElement`);
expect(calls).not.toContain(`${fn} -> app.tsx:App::mutateElement`);
}
} finally {
cg.close();
}
});

it("excalidraw's shape: a generic alias in another file, multi-line, with type parameters", async () => {
const { cg } = await indexed({
'src/scene.ts': SCENE_TS,
'src/app.tsx': APP_TSX,
'src/DragInput.tsx': `import type { Scene } from './scene';
export type DragInputCallbackType<
P extends string,
E = number,
> = (props: {
accumulatedChange: number;
originalElements: readonly E[];
scene: Scene;
nextValue?: number;
property: P;
setInputValue: (value: number) => void;
}) => void;
`,
'src/Angle.tsx': `import type { DragInputCallbackType } from './DragInput';

const handleDegreeChange: DragInputCallbackType<'angle'> = ({
accumulatedChange,
scene,
property,
}) => {
scene.mutateElement(accumulatedChange);
};

export default handleDegreeChange;
`,
});
try {
const calls = callsFrom(cg, 'src/Angle.tsx');
expect(calls).toContain('handleDegreeChange -> scene.ts:Scene::mutateElement');
expect(calls).not.toContain('handleDegreeChange -> app.tsx:App::mutateElement');
} finally {
cg.close();
}
});

it('an inline function type, and an alias declared in the same file', async () => {
const { cg } = await indexed({
'src/scene.ts': SCENE_TS,
'src/app.tsx': APP_TSX,
'src/use.tsx': `import { Scene } from './scene';
type Local = (s: Scene) => void;
export const inline: (scene: Scene) => void = (scene) => {
scene.mutateElement(1);
};
export const local: Local = (s) => {
s.mutateElement(1);
};
`,
});
try {
const calls = callsFrom(cg, 'src/use.tsx');
expect(calls).toContain('inline -> scene.ts:Scene::mutateElement');
expect(calls).toContain('local -> scene.ts:Scene::mutateElement');
} finally {
cg.close();
}
});

it("reads nothing for a member typed by the alias's own type parameter", async () => {
const { cg } = await indexed({
'src/scene.ts': SCENE_TS,
'src/types.ts': `export type Cb<Scene> = (props: { scene: Scene }) => void;
`,
'src/use.tsx': `import type { Cb } from './types';
import { Scene } from './scene';
export const h: Cb<Scene> = ({ scene }) => {
scene.mutateElement(1);
};
`,
});
try {
// `Scene` in the alias is its type parameter, which this reading doesn't
// substitute: the call is read as before, which links nothing here (a
// `.tsx` call takes no lone `.ts` method by name).
expect(callsFrom(cg, 'src/use.tsx').filter((c) => c.startsWith('h -> '))).toEqual([]);
} finally {
cg.close();
}
});

// Three classes with a `go`, so a call nothing types links nothing by name.
const ABG = `export class Alpha { go(): void {} }
export class Beta { go(): void {} }
export class Gamma { go(): void {} }
`;

it("skips a `this` parameter on either side, as positions don't count it", async () => {
const { cg } = await indexed({
'src/abg.ts': ABG,
'src/use.ts': `import { Alpha, Beta } from './abg';
type H = (this: Window, x: Alpha, y: Beta) => void;
export const h: H = (x, y) => {
y.go();
};
type F = (p: { s: Alpha }, q: { s: Beta }) => void;
export const f: F = function (this: Window, { s }) {
s.go();
};
`,
});
try {
const calls = callsFrom(cg, 'src/use.ts');
expect(calls).toContain('h -> abg.ts:Beta::go');
expect(calls).not.toContain('h -> abg.ts:Alpha::go');
expect(calls).toContain('f -> abg.ts:Alpha::go');
expect(calls).not.toContain('f -> abg.ts:Beta::go');
} finally {
cg.close();
}
});

it('reads only the declaration the function is the value of (no semicolons)', async () => {
const { cg } = await indexed({
'src/abg.ts': ABG,
'src/use.ts': `import { Alpha, Beta } from './abg'
type OnBeta = (b: Beta) => void
let done: (x: Alpha) => void
export const handler = (r) => {
r.go()
}
export const box = { onClick: null as unknown }
let fallback: (x: Alpha) => void
box.onClick = (r) => {
r.go()
}
let count: number
export const kept: OnBeta = (b) => {
b.go()
}
`,
});
try {
const calls = callsFrom(cg, 'src/use.ts');
expect(calls).not.toContain('handler -> abg.ts:Alpha::go');
expect(calls.filter((c) => c.endsWith('Alpha::go'))).toEqual([]);
expect(calls).toContain('kept -> abg.ts:Beta::go');
} finally {
cg.close();
}
});

it('reads nothing for a union or intersection of generic aliases', async () => {
const { cg } = await indexed({
'src/abg.ts': ABG,
'src/use.ts': `import { Alpha, Beta } from './abg';
type OnAlpha<T> = (a: Alpha, x: T) => void;
type OnBeta<T> = (a: Beta, x: T) => void;
export const unioned: OnAlpha<string> | OnBeta<number> = (a) => {
a.go();
};
`,
});
try {
expect(callsFrom(cg, 'src/use.ts').filter((c) => c.startsWith('unioned -> '))).toEqual([]);
} finally {
cg.close();
}
});

it('reads a member type written over several lines whole', async () => {
const { cg } = await indexed({
'src/abg.ts': ABG,
'src/use.ts': `import { Alpha, Beta } from './abg';
type H = (p: {
s: Alpha
| Beta
t: Alpha |
Beta
}) => void;
export const h: H = ({ s, t }) => {
s.go();
t.go();
};
`,
});
try {
// \`Alpha | Beta\` is no one type: the reading gives nothing.
expect(callsFrom(cg, 'src/use.ts').filter((c) => c.startsWith('h -> '))).toEqual([]);
} finally {
cg.close();
}
});

it('reads past a comment before the arrow, and a comma inside a string or template literal type', async () => {
const { cg } = await indexed({
'src/abg.ts': ABG,
'src/use.ts': `import { Alpha, Beta, Gamma } from './abg';
type OnAlpha = (a: Alpha) => void;
export const commented: OnAlpha = /* handler */ (a) => {
a.go();
};
export const lineCommented: OnAlpha = // handler
(a) => {
a.go();
};
type F = (a: 'x,y', b: Beta, c: Gamma) => void;
export const quoted: F = (a, b, c) => {
c.go();
};
type G = (a: \`x,y\`, b: Beta, c: Gamma) => void;
export const templated: G = (a, b, c) => {
c.go();
};
`,
});
try {
const calls = callsFrom(cg, 'src/use.ts');
expect(calls).toContain('commented -> abg.ts:Alpha::go');
expect(calls).toContain('lineCommented -> abg.ts:Alpha::go');
expect(calls).toContain('quoted -> abg.ts:Gamma::go');
expect(calls).not.toContain('quoted -> abg.ts:Beta::go');
expect(calls).toContain('templated -> abg.ts:Gamma::go');
expect(calls).not.toContain('templated -> abg.ts:Beta::go');
} finally {
cg.close();
}
});

it('follows the alias after a sync of its file', async () => {
const { cg, root } = await indexed({
'src/scene.ts': SCENE_TS,
'src/app.tsx': APP_TSX,
'src/types.ts': `import type { Scene } from './scene';
export type OnChange = (props: { scene: Scene }) => void;
`,
'src/use.tsx': `import type { OnChange } from './types';
export const h: OnChange = ({ scene }) => {
scene.mutateElement(1);
};
`,
});
try {
expect(callsFrom(cg, 'src/use.tsx')).toContain('h -> scene.ts:Scene::mutateElement');
write(root, {
'src/types.ts': `import type { App } from './app';
export type OnChange = (props: { scene: App }) => void;
`,
});
await cg.sync();
const calls = callsFrom(cg, 'src/use.tsx');
expect(calls).toContain('h -> app.tsx:App::mutateElement');
expect(calls).not.toContain('h -> scene.ts:Scene::mutateElement');
} finally {
cg.close();
}
});
});
Loading