Skip to content

Fix typedef binding with CJS exports= #826

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

Open
wants to merge 5 commits into
base: main
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
32 changes: 31 additions & 1 deletion internal/binder/binder.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ type Binder struct {
flowNodePool core.Pool[ast.FlowNode]
flowListPool core.Pool[ast.FlowList]
singleDeclarationsPool core.Pool[*ast.Node]
delayedTypeAliases []*ast.Node
}

type ActiveLabel struct {
Expand Down Expand Up @@ -124,9 +125,32 @@ func bindSourceFile(file *ast.SourceFile, options *core.SourceFileAffectingCompi
b.bind(file.AsNode())
file.SymbolCount = b.symbolCount
file.ClassifiableNames = b.classifiableNames
b.delayedBindJSDocTypedefTag()
})
}

// top-level typedef binding is delayed because it changes based on whether `module.exports = x` is bound
func (b *Binder) delayedBindJSDocTypedefTag() {
if b.delayedTypeAliases == nil {
return
}
if b.file.Symbol != nil {
if exportEq := b.file.Symbol.Exports[ast.InternalSymbolNameExportEquals]; exportEq != nil && b.file.CommonJSModuleIndicator != nil {
for _, node := range b.delayedTypeAliases {
b.declareSymbol(ast.GetSymbolTable(&exportEq.Exports), exportEq /*parent*/, node, ast.SymbolFlagsTypeAlias, ast.SymbolFlagsTypeAliasExcludes)
Copy link
Member

@weswigham weswigham Apr 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This works for one level of indirection to a local namespace-y thing, but what about an aliased namespacey thing? Eg

const mod = require("./mod.js")
/**
* @typedef {string} T
*/
module.exports = mod

or, abusing a ts construct to do it locally,

namespace ns {
  export namespace inner {}
}
import mod = ns.inner
/**
* @typedef {string} T
*/
module.exports = mod

mod's symbol will be an alias, and this will just patch the typedefs onto the alias symbol, and not the alias symbol's ultimate target, which, dollars to donuts, means it's going to effectively go missing without extra lookup logic in the checker, similar to what we used to have. 🥹

Copy link
Member Author

@sandersn sandersn Apr 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even simpler, this also reproduces the problem.

function f() { }
/** @typedef {string} T */
module.exports = f

b.declareSymbol(ast.GetLocals(b.file.AsNode()), b.file.Symbol, node, ast.SymbolFlagsTypeAlias, ast.SymbolFlagsTypeAliasExcludes)
}
return
}
}
// bind normally
b.container = b.file.AsNode()
b.blockScopeContainer = b.file.AsNode()
for _, node := range b.delayedTypeAliases {
b.bindBlockScopedDeclaration(node, ast.SymbolFlagsTypeAlias, ast.SymbolFlagsTypeAliasExcludes)
}
}

func (b *Binder) newSymbol(flags ast.SymbolFlags, name string) *ast.Symbol {
b.symbolCount++
result := b.symbolPool.New()
Expand Down Expand Up @@ -686,8 +710,14 @@ func (b *Binder) bind(node *ast.Node) bool {
b.bindBlockScopedDeclaration(node, ast.SymbolFlagsInterface, ast.SymbolFlagsInterfaceExcludes)
case ast.KindCallExpression:
b.bindCallExpression(node)
case ast.KindTypeAliasDeclaration, ast.KindJSTypeAliasDeclaration:
case ast.KindTypeAliasDeclaration:
b.bindBlockScopedDeclaration(node, ast.SymbolFlagsTypeAlias, ast.SymbolFlagsTypeAliasExcludes)
case ast.KindJSTypeAliasDeclaration:
if b.file.AsNode() == b.container {
b.delayedTypeAliases = append(b.delayedTypeAliases, node)
} else {
b.bindBlockScopedDeclaration(node, ast.SymbolFlagsTypeAlias, ast.SymbolFlagsTypeAliasExcludes)
}
case ast.KindEnumDeclaration:
b.bindEnumDeclaration(node)
case ast.KindModuleDeclaration:
Expand Down
38 changes: 32 additions & 6 deletions internal/checker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -13618,7 +13618,7 @@ func (c *Checker) getTargetOfImportEqualsDeclaration(node *ast.Node, dontResolve
moduleReference = getExternalModuleImportEqualsDeclarationExpression(node)
}
immediate := c.resolveExternalModuleName(node, moduleReference, false /*ignoreErrors*/)
resolved := c.resolveExternalModuleSymbol(immediate, false /*dontResolveAlias*/)
resolved := c.resolveExternalModuleSymbol(immediate, dontResolveAlias)
c.markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, false /*overwriteEmpty*/, nil, "")
return resolved
}
Expand Down Expand Up @@ -14545,9 +14545,24 @@ func (c *Checker) resolveEntityName(name *ast.Node, meaning ast.SymbolFlags, ign
}

func (c *Checker) resolveQualifiedName(name *ast.Node, left *ast.Node, right *ast.Node, meaning ast.SymbolFlags, ignoreErrors bool, dontResolveAlias bool, location *ast.Node) *ast.Symbol {
namespace := c.resolveEntityName(left, ast.SymbolFlagsNamespace, ignoreErrors, false /*dontResolveAlias*/, location)
namespace := c.resolveEntityName(left, ast.SymbolFlagsNamespace, true /*ignoreErrors*/, false /*dontResolveAlias*/, location)
if namespace == nil || ast.NodeIsMissing(right) {
return nil
var immediate *ast.Symbol
alias := c.resolveEntityName(left, ast.SymbolFlagsAlias, true /*ignoreErrors*/, true /*dontResolveAlias*/, location)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm. So if the resolution of the LHS of a qualified name fails, we try to look it up with only one level of aliasing? This seems... weird? While this might work in some scenarios, if getExportsOfSymbol doesn't return the merged in aliases, declaration emit is going to struggle to figure out how to name these typedefs, as traversing the exports is how symbols are named. Basically, we'd like to interpret

/**
* @typedef {number} Foo
*/
module.exports = name

as

export * from name // even though this isn't a thing in ESM (yet)
export type Foo = number

I think if we want to handle this in a non-jank way, we need to bind a module.exports = name in a file with typedefs not as an alias but instead as a (new?) namespacey symbol kind that has logic in getExportsOfSymbol to merge together the typedef set and the resolved, late-bound alias's set. (Once again, a callback to the .cjsSymbolMerged logic we used to have)

I'm also honestly a lil unsure what a syntactically driven declaration emit for this is.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we just add support for parsing/checking export * from name in declaration files and actually do that transform on reparse? In theory it'll be added to esm alongside the module declarations proposal, probably.

if alias != nil {
immediate = c.getImmediateAliasedSymbol(alias)
if immediate != nil && !core.Some(immediate.Declarations, func(d *ast.Node) bool { return d.Kind == ast.KindJSExportAssignment }) {
immediate = nil
}
}
if immediate == nil {
if !ignoreErrors {
c.resolveEntityName(left, ast.SymbolFlagsNamespace, ignoreErrors, false /*dontResolveAlias*/, location)
}
return nil
} else {
namespace = immediate
}
}
if namespace == c.unknownSymbol {
return namespace
Expand Down Expand Up @@ -22830,9 +22845,20 @@ func (c *Checker) getTypeFromImportTypeNode(node *ast.Node) *Type {
}
next := core.OrElse(symbolFromModule, symbolFromVariable)
if next == nil {
c.error(current, diagnostics.Namespace_0_has_no_exported_member_1, c.getFullyQualifiedName(currentNamespace, nil), scanner.DeclarationNameToString(current))
links.resolvedType = c.errorType
return links.resolvedType
var symbolFromImmediateModule *ast.Symbol
if currentNamespace == moduleSymbol {
immediateModuleSymbol := c.resolveExternalModuleSymbol(innerModuleSymbol, true /*dontResolveAlias*/)
if immediateModuleSymbol != nil && core.Some(immediateModuleSymbol.Declarations, func(d *ast.Node) bool { return d.Kind == ast.KindJSExportAssignment }) {
symbolFromImmediateModule = c.getSymbol(c.getExportsOfSymbol(immediateModuleSymbol), current.Text(), meaning)
}
}
if symbolFromImmediateModule != nil {
next = symbolFromImmediateModule
} else {
c.error(current, diagnostics.Namespace_0_has_no_exported_member_1, c.getFullyQualifiedName(currentNamespace, nil), scanner.DeclarationNameToString(current))
links.resolvedType = c.errorType
return links.resolvedType
}
}
c.symbolNodeLinks.Get(current).resolvedSymbol = next
c.symbolNodeLinks.Get(current.Parent).resolvedSymbol = next
Expand Down
1 change: 0 additions & 1 deletion internal/parser/reparser.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ func (p *Parser) reparseTags(parent *ast.Node, jsDoc []*ast.Node) {
for _, tag := range j.AsJSDoc().Tags.Nodes {
switch tag.Kind {
case ast.KindJSDocTypedefTag:
// !!! Don't mark typedefs as exported if they are not in a module
typeExpression := tag.AsJSDocTypedefTag().TypeExpression
if typeExpression == nil {
break
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
input.js(5,48): error TS2304: Cannot find name 'P'.
input.js(48,1): error TS2309: An export assignment cannot be used in a module with other exported elements.
input.js(52,17): error TS2322: Type '{ color: string; }' is not assignable to type '{ color: "blue" | "red"; }'.
Types of property 'color' are incompatible.
Type 'string' is not assignable to type '"blue" | "red"'.


==== input.js (3 errors) ====
==== input.js (2 errors) ====
/** @typedef {{ color: "red" | "blue" }} MyComponentProps */

/**
Expand Down Expand Up @@ -56,12 +55,8 @@ input.js(52,17): error TS2322: Type '{ color: string; }' is not assignable to ty
* @type {MyComponentProps}
*/
module.exports = {
~~~~~~~~~~~~~~~~~~
color: "red"
~~~~~~~~~~~~~~~~
}
~
!!! error TS2309: An export assignment cannot be used in a module with other exported elements.

expectLiteral({ props: module.exports });
~~~~~
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
index.js(9,1): error TS2309: An export assignment cannot be used in a module with other exported elements.
index.js(9,34): error TS7006: Parameter 'options' implicitly has an 'any' type.


==== index.js (2 errors) ====
==== index.js (1 errors) ====
/**
* @typedef Options
* @property {string} opt
Expand All @@ -12,8 +11,6 @@ index.js(9,34): error TS7006: Parameter 'options' implicitly has an 'any' type.
* @param {Options} options
*/
module.exports = function loader(options) {}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2309: An export assignment cannot be used in a module with other exported elements.
~~~~~~~
!!! error TS7006: Parameter 'options' implicitly has an 'any' type.

Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
typescript-eslint.js(12,17): error TS7019: Rest parameter 'configs' implicitly has an 'any[]' type.
typescript-eslint.js(14,1): error TS2309: An export assignment cannot be used in a module with other exported elements.


==== eslint.config.js (0 errors) ====
Expand All @@ -26,7 +25,7 @@ typescript-eslint.js(14,1): error TS2309: An export assignment cannot be used in
},
};

==== typescript-eslint.js (2 errors) ====
==== typescript-eslint.js (1 errors) ====
/**
* @typedef {{ rules: Record<string, boolean> }} Plugin
*/
Expand All @@ -43,6 +42,4 @@ typescript-eslint.js(14,1): error TS2309: An export assignment cannot be used in
!!! error TS7019: Rest parameter 'configs' implicitly has an 'any[]' type.

module.exports = { config };
~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2309: An export assignment cannot be used in a module with other exported elements.

Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ import { writeFile, WriteFileOptions, WriteFileOptions as OtherName } from "fs";
/** @typedef {{ x: any }} JSDocType */

export { JSDocType };
>JSDocType : Symbol(JSDocType, Decl(index.js, 2, 4), Decl(index.js, 4, 8))
>JSDocType : Symbol(JSDocType, Decl(index.js, 4, 8), Decl(index.js, 2, 4))

export { JSDocType as ThisIsFine };
>JSDocType : Symbol(JSDocType, Decl(index.js, 2, 4), Decl(index.js, 4, 8))
>JSDocType : Symbol(JSDocType, Decl(index.js, 4, 8), Decl(index.js, 2, 4))
>ThisIsFine : Symbol(ThisIsFine, Decl(index.js, 5, 8))

export { WriteFileOptions };
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
context.js(4,14): error TS1340: Module './timer' does not refer to a type, but is used as a type here. Did you mean 'typeof import('./timer')'?
context.js(5,14): error TS1340: Module './hook' does not refer to a type, but is used as a type here. Did you mean 'typeof import('./hook')'?
context.js(6,31): error TS2694: Namespace 'Hook' has no exported member 'HookHandler'.
context.js(34,14): error TS2350: Only a void function can be called with the 'new' keyword.
context.js(48,1): error TS2309: An export assignment cannot be used in a module with other exported elements.
hook.js(2,20): error TS1340: Module './context' does not refer to a type, but is used as a type here. Did you mean 'typeof import('./context')'?
hook.js(10,1): error TS2309: An export assignment cannot be used in a module with other exported elements.


==== timer.js (0 errors) ====
Expand All @@ -15,7 +12,7 @@ hook.js(10,1): error TS2309: An export assignment cannot be used in a module wit
this.timeout = timeout;
}
module.exports = Timer;
==== hook.js (2 errors) ====
==== hook.js (1 errors) ====
/**
* @typedef {(arg: import("./context")) => void} HookHandler
~~~~~~~~~~~~~~~~~~~
Expand All @@ -28,10 +25,8 @@ hook.js(10,1): error TS2309: An export assignment cannot be used in a module wit
this.handle = handle;
}
module.exports = Hook;
~~~~~~~~~~~~~~~~~~~~~
!!! error TS2309: An export assignment cannot be used in a module with other exported elements.

==== context.js (5 errors) ====
==== context.js (3 errors) ====
/**
* Imports
*
Expand All @@ -42,8 +37,6 @@ hook.js(10,1): error TS2309: An export assignment cannot be used in a module wit
~~~~~~~~~~~~~~~~
!!! error TS1340: Module './hook' does not refer to a type, but is used as a type here. Did you mean 'typeof import('./hook')'?
* @typedef {import("./hook").HookHandler} HookHandler
~~~~~~~~~~~
!!! error TS2694: Namespace 'Hook' has no exported member 'HookHandler'.
*/

/**
Expand Down Expand Up @@ -88,6 +81,4 @@ hook.js(10,1): error TS2309: An export assignment cannot be used in a module wit
}
}
module.exports = Context;
~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2309: An export assignment cannot be used in a module with other exported elements.

Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,19 @@ module.exports = Hook;
*/

function Context(input) {
>Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: any) => State; }; }
>Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: HookHandler) => State; }; }
>input : Input

if (!(this instanceof Context)) {
>!(this instanceof Context) : boolean
>(this instanceof Context) : boolean
>this instanceof Context : boolean
>this : any
>Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: any) => State; }; }
>Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: HookHandler) => State; }; }

return new Context(input)
>new Context(input) : any
>Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: any) => State; }; }
>Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: HookHandler) => State; }; }
>input : Input
}
this.state = this.construct(input);
Expand All @@ -107,21 +107,21 @@ function Context(input) {
>input : Input
}
Context.prototype = {
>Context.prototype = { /** * @param {Input} input * @param {HookHandler=} handle * @returns {State} */ construct(input, handle = () => void 0) { return input; }} : { construct: (input: Input, handle?: any) => State; }
>Context.prototype : { construct: (input: Input, handle?: any) => State; }
>Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: any) => State; }; }
>prototype : { construct: (input: Input, handle?: any) => State; }
>{ /** * @param {Input} input * @param {HookHandler=} handle * @returns {State} */ construct(input, handle = () => void 0) { return input; }} : { construct: (input: Input, handle?: any) => State; }
>Context.prototype = { /** * @param {Input} input * @param {HookHandler=} handle * @returns {State} */ construct(input, handle = () => void 0) { return input; }} : { construct: (input: Input, handle?: HookHandler) => State; }
>Context.prototype : { construct: (input: Input, handle?: HookHandler) => State; }
>Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: HookHandler) => State; }; }
>prototype : { construct: (input: Input, handle?: HookHandler) => State; }
>{ /** * @param {Input} input * @param {HookHandler=} handle * @returns {State} */ construct(input, handle = () => void 0) { return input; }} : { construct: (input: Input, handle?: HookHandler) => State; }

/**
* @param {Input} input
* @param {HookHandler=} handle
* @returns {State}
*/
construct(input, handle = () => void 0) {
>construct : (input: Input, handle?: any) => State
>construct : (input: Input, handle?: HookHandler) => State
>input : Input
>handle : any
>handle : HookHandler
>() => void 0 : () => any
>void 0 : undefined
>0 : 0
Expand All @@ -131,9 +131,9 @@ Context.prototype = {
}
}
module.exports = Context;
>module.exports = Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: any) => State; }; }
>module.exports : { (input: Input): any; prototype: { construct: (input: Input, handle?: any) => State; }; }
>module : { Context: { (input: Input): any; prototype: { construct: (input: Input, handle?: any) => State; }; }; }
>exports : { (input: Input): any; prototype: { construct: (input: Input, handle?: any) => State; }; }
>Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: any) => State; }; }
>module.exports = Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: HookHandler) => State; }; }
>module.exports : { (input: Input): any; prototype: { construct: (input: Input, handle?: HookHandler) => State; }; }
>module : { Context: { (input: Input): any; prototype: { construct: (input: Input, handle?: HookHandler) => State; }; }; }
>exports : { (input: Input): any; prototype: { construct: (input: Input, handle?: HookHandler) => State; }; }
>Context : { (input: Input): any; prototype: { construct: (input: Input, handle?: HookHandler) => State; }; }

Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ file.js(10,51): error TS2300: Duplicate identifier 'myTypes'.
file.js(13,13): error TS2300: Duplicate identifier 'myTypes'.
file.js(18,15): error TS2702: 'myTypes' only refers to a type, but is being used as a namespace here.
file.js(18,39): error TS2300: Duplicate identifier 'myTypes'.
file.js(20,9): error TS2300: Duplicate identifier 'myTypes'.
file2.js(6,11): error TS2315: Type 'Object' is not generic.
file2.js(12,23): error TS2702: 'myTypes' only refers to a type, but is being used as a namespace here.
file2.js(17,12): error TS2702: 'testFnTypes' only refers to a type, but is being used as a namespace here.


==== file.js (5 errors) ====
==== file.js (6 errors) ====
/**
* @namespace myTypes
* @global
Expand Down Expand Up @@ -39,6 +40,8 @@ file2.js(17,12): error TS2702: 'testFnTypes' only refers to a type, but is being
!!! error TS2300: Duplicate identifier 'myTypes'.

export {myTypes};
~~~~~~~
!!! error TS2300: Duplicate identifier 'myTypes'.
==== file2.js (3 errors) ====
import {myTypes} from './file.js';

Expand Down
Loading