Previously, intersections were only allowed as targets, but this was
just an artifact of the original implementation, which operated inside
the structural part of isRelatedTo. Removing this restriction catches
subtle bugs in React user code, where a function named `create` returns
a mapped type whose types are all branded numbers. The display of these
properties, for some original type `T`, is not `number & { __ }` but
the much-less-obvious `RegisteredStyle<T>`.
Previously, getWidenedTypedFromJSPropertyAssignment was not called for
Typescript code. Since property assignments on functions, it is. That
meant that property assignments would incorrectly create a JS container
for empty object literals in a property assignment, even in Typescript:
```ts
const one = () => 1
one.p = {}
one.p.q = {} // should not work in Typescript!
```
Now empty object literals never create expando objects in Typescript,
because getJSExpandoObjectType requires the declaration to be in a JS
file.
skipping narrowing if the old algorithm produces a type to which the
assigned type is not assignable.
This also means we'll no longer narrow for erroneous assignments where
the assigned type is not assignable to the declared type. This is the
reason for the numericLiteralTypes3 baseline change.
Fixes#26405.
Previously, they were mistakenly treated as private because of a check
that required all super property accesses (like `super.x()`) to be
references to a MethodDeclaration or MethodSignature. This change also
allows PrototypeProperty special assignment kinds.
* Allow special property assignments in TS
But only for functions and constant variable declarations initialised with
functions.
This specifically excludes class declarations and class expressions,
which differs from Javascript. That's because Typescript supports
`static` properties, which are equivalent to property assignments to a
class.
* Improve contextual typing predicate
Don't think it's right yet, but probably closer?
* More fixes.
The code is still fantastically ugly, but everything works the way it
should.
Also update baselines, even where it is ill-advised.
* Cleanup
* Remove extra whitespace
* Some kind of fix to isAnyDeclarationName
It's not done yet.
Specifically, in TS:
Special property assignments are supposed to be declaration sites (but not all
top-level assignments), and I think I
got them to be. (But not sure).
In JS:
Special property assignments are supposed to be declaration sites (but not all
top-level assignments), and I'm pretty sure ALL top-level assignments
have been declaration sites for some time. This is incorrect, and
probably means the predicate needs to be the same for both dialects.
* Add fourslash and improve isAnyDeclarationName
Now JS behaves the same as TS.
* Cleanup from PR comments
* This-property w/empty object init: use type annotation
* JS initializer type doesn't apply to this-property assignments
* Move getJSExpandoType into getWidenedType* functions
Plus some cleanup.
* Improved style from PR comments
* Parameters are not expando
* Classes can extend JS constructor functions
Now ES6 classes can extend ES5 constructor functions, although only
those written in a JS file.
Note that the static side assignability is checked. I need to write
tests to make sure that instance side assignability is checked too.
I haven't tested generic constructor functions yet either.
* Test static+instance assignability errors+generics
Note that generics do not work.
* Cleanup from PR comments
* Even more cleanup
* Update case of function name
* Fixes#26128 - signature comp for jsdoc @class.
Another issue caused by js functions tagged with jsdoc
`@constructor` not having construct signatures.
A jsdoc function type that constructs a type (`function(new: Ex)`),
has a construct signature and return value inferred as the
constructed type where as a jsdoc `@constructor` has no construct
signatures, and it's call signature has a void return type
(or undefined).
i.e:
```javascript
/** @constructor **/ function E() {};
// typeof E -> call signature: () => void
/** @param {function(new: E)} d */ function c(d) {}
// typeof d -> construct: () => E
```
--
This commit fixes this (in an inelegant way) by considering `@class` function signatures as construct signatures and synthesizing it's return value _only for signature comparison_.
There might be a slight performance hit, since the synthesized return value is not cached; but changing the `@class` function's return type in `getReturnTypeOfSignature` causes other issues.
* Update jsdoc function test to fix mistake.
* Allow type predicates
1. Parse type predicates. Note that they are parsed everywhere, and get
the appropriate error when used places besides a return type.
2. When creating a type predicate, correctly find the function's parameters
starting from the jsdoc return type.
* Fix type of TypePredicateNode.parent: add JSDocTypeExpression
* Update API baselines
* Handle JSDoc signature inside @type annotations
* Fix circularity when getting type predicates
Also move createTypePredicateFromTypePredicateNode closer to its use
* More cleanup based on review comments
typeMaybeAssignableTo.
typeMaybeAssignableTo decomposed unions at the top level of the assigned
type but didn't properly handle other unions that arose during
assignability checking, e.g., in the constraint of a generic lookup
type.
Fixes#26130.
* Fixes#26122.
When `resolveCall` does not resolve in `resolveNewExpression`, the error should only be thrown if there is a *defined* signature that is not-void.
* Fix other baselines to remove erroneous TS2350.
unmangled package name where appropriate.
Add a test case for an untyped sub-module of a scoped package with
typings. The other diagnostic message is covered by existing tests; I
guess no one looked at the baselines closely enough.
Fixes#23999.
* Properly infer `this` in tagged `@constructor`s.
`c.prototype.method = function() { this }` was already supported.
This commit add support to two more kinds relying on the JSDoc
`@constructor` tag. These are:
1. `/** @constructor */ function Example() { this }`
2. `/** @constructor */ var Example = function() { this }`
* Update the baseline for js constructorFunctions.
C3 and C4 `this` was set as `any`, now it is properly showing as
the class type.
* Fix lint errors
* Add circular initialisers to constructo fn tests.
* Error (`TS2348`) if calling tagged js constructors
When calling a JS function explicitly tagged with either `@class` or
`@constructor` the checker should throw a TS2348 not callable error.
* Don't resolve jsdoc classes with construct sigs.
This undoes the last commit that sought to change how js functions
tagged with `@class` were inferred. For some reason, currently
unknown, giving those functions construct signatures causes issues
in property assignment/member resolution (as seen in the
`typeFromPropertyAssignment12` test case).
Instead of changing the signature resolution, the error is explicitly
generated in `resolveCallExpression` for those functions.
* In JSDoc, resolve import types as values too
This is something that we probably should have been doing for some time.
Fixes#26049
* Fix whitespace lint
* Only bind module.exports if no local definition exists
Note that this uses `lookupSymbolForNameWorker`, which is really a
best-effort check since it only knows about symbols that it has already
encountered.
As a side-effect, even when `module` is bound as part of a
`module.exports` reference, it only declares it once instead of one
declaration per reference.
* Only type module.exports inside module files
It is an error inside script files, but the binder sometimes creates a
ModuleExports symbol because we doesn't know whether we have a commonjs
module until after binding is done.
* Only bind module.exports in a commonjs module
Note that this, too, is a best-effort check since evidence of
commonjs-ness may be found after a *reference* to module.exports. (A
reference to module.exports alone is not enough evidence that a file is
commonjs. It has to have an assignment to it.)
* Support the JSDoc @enum tag
`@enum` is used on a variable declaration with an object literal
initializer. It does a number of things:
1. The object literal has a closed set of properties, unlike other
object literals in Javascript.
2. The variable's name is resolvable as a type, but it just has the
declared type of the enum tag.
3. Each property's type must be assignable to the enum tag's declared type,
which can be any type.
For example,
```js
/** @enum {string} */
const Target = {
START: "START",
END: "END",
MISTAKE: 0, // error 'number' is not assignable to 'string' -- see (3)
}
Target.THIS_IS_AN_ERROR; // See (1)
/** @type {Target} See (2) */
var target = Target.START;
```
* Fix lint, add new test case, update API baselines
* Revert "Revert "Explicitly typed special assignments are context sensitive (#25619)""
This reverts commit 16676f2707.
* Revert "Revert "Explicitly typed prototype assignments are context sensitive (#25688)""
This reverts commit ff8c30d636.
* Initial, wasteful, solution
It burns a check flags. Probably necessary, but perhaps not.
I haven't accepted baselines, but they are a bit questionable. I'm not
sure the synthetic type is right, because I expected to see
{ "exports": typeof import("x") } but instead see { "x": typeof
import("x") }.
* Update some baselines
* module.exports= always uses lhs type
Conflicts between exports property assignments and exports assignments
should get a union type instead of an error.
* Fix lint and accept good user baselines
* Add tests based on user tests.
These currently fail.
* Fix all but 1 of user test bugs found by typing module.exports
Still quite messy and full of notes
* Follow merged symbols+allow any object type
This allows exports like `module.exports = new EE` to have properties
added to them.
Still messy, but I'm going to run user tests and look for regressions.
* Update improved user baselines
* Fix infinite recursion when checking module.exports
* Fix bogus use-before-def error
getExportSymbolOfValueSymbolIfExported should always merge its returned
symbol, whether it's symbol.exportSymbol or just symbol.
* Update user test baselines
* Cleanup
* More small cleanup
* Bind `module` of `module.exports` as a special symbol
Previously it was also special, but created during name resolution in
the checker. It made sense when there was only one special symbol for
all files, but now there is one `module` symbol per file.
* Fix parsing of parenthesized JSDoc parameters
Parenthesis can start a jsdoc function parameter since it is just a
type, and parenthesis can start a type:
```js
/** @type {function(((string))): void} */
```
However, this is not legal in other parameter lists:
```ts
function x((((a))): string) { }
```
This change makes jsdoc function parameter lists parse differently than
normal parameter lists by allowing parenthesis as a start character of
jsdoc parameters.
* Parse nested uses of jsdoc function types
* Fix test
* add grammar check for labeled function declaration
* fix debug failed on labeled class declaration
* move labeled statement check to binder and add more pattern for check
* update diagnostic message
* update baseline
* Explicitly typed prototype assignments:ctx sensitive
Follow up to #25619: Add the necessary code to type `prototype`
correctly in prototype assignments so that code like
`F.prototype = { ... }` properly makes the object literal context
sensitive.
* Fix lint
* Explicitly typed js assignments: context sensitive
Explicitly typed special assignments should be context sensitive if they
have an explicit type tag. Previously no special assignments were
context sensitive because they are declarations, and in the common,
untyped, case we inspect the right side of the assignment to get the
type of the left side, and inspect the right side of the assignment to
get the type of the left side, etc etc.
Note that some special assignments still return `any` from
checkExpression, so still don't get the right type.
Fixes#25571
* Change prototype property handling+update bselines
* Fix indentation in test
* Update baselines
* Get return type from `@type` tag
This only happens in the checker, where the type is easily accessible.
The syntax-based check in getEffectiveReturnTypeNode as a fast path, and
for other uses that don't want to make a call to getTypeFromTypeNode.
Fixes#25525
* Implement PR suggestions
* Error when type tag isn't callable
* Fix lint
Previously it did not, causing misleading excess property errors. Note
that assignability errors with conditional types are still usually
confusing. This PR doesn't address that.
Also, make sure that exact matches in getSpellingSuggestion are skipped.
Block scoped variables, classes and enums would issue a bogus
use-before-def error in jsdoc because name resolution always adds Value,
even when resolving a type.
Fixes#25097
* get return type from `@type` tags
Previously, getJSDocReturnType did not check the `@type` tag for a type
node that has a return type. Now it does.
* Improve doc comment of getJSDocReturnType
* More type predicates in type guards!
* Update API baselines with new documentation (?!)
* Index signatures contribute properties to unions
This means that in a union like this:
```ts
type T = { foo: number } | { [s: string]: string }
```
`foo` is now a property of `T` with type `number | string`. Previously
it was not.
Two points of interest:
1. A readonly index signature makes the resulting union property readonly.
2. A numeric index signature only contributes number-named properties.
Fixes#21141
* Correctly handle numeric and symbol property names
1. Symbol-named properties don't contribute to unions.
2. Number-named properties should use the numeric index signature type,
if present, and fall back to the string index signature type, not the
other way round.
Previously variable declaration+function expression worked.
Note that class expression/class declaration do not work, due to the way
they are specified. I added a test for future reference.
* Adds related spans and error grouping for duplicate identifier errors
* Trim trailing whitespace
* Record related info in error baselines
* Make error more whimsical
* Destructuring declaration prefers type annotation type
Previously, getTypeForBindingElement would always union the declarations type and
the type of the default initializer. Now, if the declaration has a type
annotation, it does not union with the initializer type. The type
annotation's type is the one used.
* Small cleanup in parentDeclarationHasTypeAnnotation
* Refactoring based on PR comments
* Combine getCombined*Flags into a single helper function
Retain the individual functions since they are used a lot.
* Remove unneeded temp
* Fix duplicate errors in js special assignments
* Simplify checkExpressionCached call to checkExpression
* Accept baselines after merge
* Use Map for deferredNodes and improve NoDeferredCheck comment
I added an assert when a duplicate was added, but it caused 18 failures
in our test suite.
* Remove NoDeferredCheck
That is, only nest them if their name matches the provided parent name.
Otherwise do not nest them.
Note that this commit changes the behaviour of an incorrect typedef that
contains both an `@type` child tag and `@property` child tags.
Previously, the `@type` would be incorrectly nested under a `@property`
tag with type `object`, just like `@property` tags would be. Now, the
`@type` tag causes the entire typedef to ignore the `@property` tags and
treat the typedef as if it were an instance of the
typedef-and-nested-type pattern:
```js
/**
* @typedef {Object} name
* @type {{ the, actual, type }}
*/
```
* Don't recommend to install '@types/foo' if that already exists
* Add different extra diagnostic text if the @types package exists
* Update API (#24966)
* getDeclarationIdentifier handles undefined name
getNameOfDeclaration actually doesn't handle all declarations, only
those that produce names that could be reasonably used as an identifier.
Until now, getDeclarationIdentifier assumed that getNameOfDeclaration
always returned a name. This caused crashes whenever we tried to get the
name of something like a Constructor.
* Add test and baselines
* getNameOfDeclaration can return undefined
This requires all callers to handle it, which turns out now to be too
disruptive.
* Fix lint
* Check extends tag first in getClassExtendsHeritageClauseElement
Previously getBaseTypeNodeOfClass checked, but this is only used in a
few places.
* Fix names and add test
* Update API baseline
* Move jsdocAugments tests to conformance/jsdoc
* Better naming in checkClassLikeDeclaration
* avoid circularity in getTypeOfVariableOrParameterOrProperty
Modify getTypeOfVariableOrParameterOrProperty to get the type of the
variable declaration before widening it. This essentially avoids some
circularities by (1) setting the type of the variable declaration to the
unwidened type (2) updating the type of the variable declaration to the
widened one.
You will still get a circular noImplicitAny in (1), for expressions that
actually are circular, but not in (2), for the containers of things that
are not themselves circular.
* Stop checking js init object literals via checkObjectLiteral
* checkBinaryExpression: new code for special assignments
* Chained lookup for js initializer type
* Check for JS-specific types only once
Also make sure to respect the type annotation if there is one.
* Accept API changes
Nearly everything in a merge of JS special assignments looks like a
valueDeclaration. This commit ensures that intermediate "module
declarations" are not used when a better valueDeclaration is available:
```js
// File1.js
var X = {}
X.Y.Z = class { }
// File2.js
X.Y = {}
```
In the above example, the `Y` in `X.Y.Z = class { }` was used as the
valueDeclaration for `Y` because it appeared before `X.Y = {}` in the
compilation.
This change exposed a bug in binding, #24703, that required a change in
typeFromPropertyAssignmentOutOfOrder. The test still fails for the
original reason it was created, and the new bug #24703 contains a repro.
Do this by not widening properties of an object literal that are
1. JS initialisers
2. and not an object literal
These properties have types that will never widen, so the compiler
shouldn't ask for the types earlier than it strictly needs to.
* Parse (and mostly support) template tag constraints
A bunch of tests hit the asserts I added though.
* Messy version is finished. Need to add a few tests
* Refactor to be smaller
* Small refactor + Add one test
* Another test
* Minor cleanup
* Fix error reporting on type parameters on ctors
* Simplify syntax of `@template` tag
This is a breaking change, but in my sample, nobody except webpack used the
erroneous syntax. I need to improve the error message, so
jsdocTemplateTag3 currently fails to remind me of that.
* Better error message for template tag
* Fix fourslash baselines
* Another fourslash update
* Address PR comments
* Simplify getEffectiveTypeParameterDeclarations
Make checkGrammarConstructorTypeParameters do a little more work
* Static assignments to class expressions work
* Bind static properties of functions too
Also update SymbolLinks in getTypeOfFuncClassEnumModule so that the
type gets cached correctly.
* Remove initializer handling:obj literals+type lookup
Also include a couple of improved baselines
* Fix 1-nested js containers:binding+cross-file merge
* Consolidate check into one utility
The utility is horrible and needs to change, but at least it's in one
place.
Next step is to make the utility like getDeclarationOfAlias, except
getDeclarationOfJSAlias.
* Defaulted assignments now (mostly) work
* Default assignment definitely work, and IIFEs kind of do
* n-nested undeclared containers now seem to work
Merging even seems to work ok.
* Handle prototype+prototype property assignments
Perhaps in the wrong way. I have an idea how to simplify them.
* Remove prototype special-case
1. It's not completely removed; the checker code in
getJavascriptClassType needs to be fixed, among other places.
2. I didn't actually remove the code so that it will be easier to see
what used to be there on Monday.
Regardless, the code will be much simpler and seems to be mostly
improved with very little work so far.
* Allow more merges+accept baselines
* Update more baselines
* Fix js initializer check in bindPropertyAssignment
* Fix codefixes
* Rest of strictNullChecks cleanup + other cleanup
1. Remove a few TODOs
2. Remove extraneous SymbolFlag
3. Simplify isSameDefaultedName
* Binder cleanup
* Checker cleanup
* Almost done with utilities cleanup
* Utilities cleanup
* Require js initializer to be (1) JS (2) initializer
Change getDeclarationOfJSInitializer to require that the provided js
initializer be in a javascript file, and that it is the initializer of
the retrieved declaration.
* Use getSymbolOfNode instead of accessing symbol directly
* Ugh. Start over with just test cases
* Handle additional cases in getTypeOfVariableOrParameterOrProperty
These are cases in a really embarrassing check, in which we admit that
the symbol flags steered us wrong and switch to
getTypeOfFuncClassEnumModule instead (which never asserts).
* Add test case for #24111
* Address PR comments
* Fix resolution of exported types in commonjs
It is fine to resolve the types of exported classes in ES6:
```js
export class C {
}
var c = new C()
```
But not for commonjs exported classes:
```js
module.exports.C = class {
}
var c = new C() // should error
```
Fixes#24492
* All jsdoc type aliases are available locally in commonjs modules
* Check that location isSourceFile before commonJsModuleIndicator
A bug in checkSpecialAssignment added bogus duplicate identifier errors
when using module.exports assignment to export a class. This commit
fixes that.
* Skip IntrinsicAttributes elaboration in JSX errors
Do not issue an error message for a source type that comes from JSX
attributes and a target type that is an intersection containing
IntrinsicAttributes or IntrinsicClassAttributes. This will make error
messages simpler and less confusing.
Note:
1. There will always be elaboration under the skipped message, so this
won't elide errors completely.
2. Rarely (once in the tests) the intersection type will have more that
one non-Intrinsic* member. However, these additional members don't
provide useful information either, so it's fine to skip them.
* Add test of IntrinsicAttributes error
* Fix indentation in test
* Callback tag:Disallow nested-object-param syntax
Previously this caused a crash in parsing. If/when we want to support
this syntax, we will need to fix this crash.
* Update baselines
* Fix JSDoc type resolution
Breaks type parameter resolution that is looked up through prototype
methods, though. I need to fix that still.
* Check for prototype method assignments first
* Undo dedupe changes to getJSDocTags
* JS Type aliases can't refer to host type params
Previously, js type aliases (@typedef and @callback) could refer to
type paremeters defined in @template tags in a *different* jsdoc tag, as
long as both tags were hosted on the same signature.
* Reduce dedupe changes+update baseline
The only reason I had undone them was to merge successfully with an
older state of master.
* Add initial tests
* Add types
* Half of parsing (builds but does not pass tests)
* Parsing done; types are uglier; doesn't crash but doesn't pass
* Bind callback tag
Builds but tests still don't pass
* Only bind param tags inside callback tags
* Fix binding switch to only handle param tags once
* Checking is 1/3 done or so.
Now I'm going to go rename some members to be more uniform. I hate
unnnecessary conditionals.
* Rename typeExpression to type (for some jsdoc)
(maybe I'll rename more later)
* Rename the rest of typeExpressions
Turns out there is a constraint in services such that they all need to
be named the same.
* Few more checker changes
* Revert "Rename the rest of typeExpressions"
This reverts commit f41a96b24d.
* Revert "Rename typeExpression to type (for some jsdoc)"
This reverts commit 7d2233a00e.
* Finish undoing typeExpression rename
* Rename and improve getTypeParametersForAliasSymbol
Plus some other small fixes
* Core checking works, but is flabbergastingly messy
I'm serious.
* Callback return types work now
* Fix crash in services
* Make github diff smaller
* Try to make github diff even smaller
* Fix rename for callback tag
* Fix nav bar for callback tag
Also clean up some now-redundant code there to find the name of typedefs.
* Handle ooorder callback tags
Also get rid of redundant typedef name code *in the binder*. It's
everywhere!
* Add ooorder callback tag test
* Parse comments for typedef/callback+display param comments
* Always export callbacks
This requires almost no new code since it is basically the same as
typedefs
* Update baselines
* Fix support for nested namespaced callbacks
And add test
* Callbacks support type parameters
1. Haven't run it with all tests
2. Haven't tested typedef tags yet
3. Still allows shared symbols when on function or class declarations.
* Template tags are now bound correctly
* Test oorder template tags
It works.
* Parser cleanup
* Cleanup types and utilities
As much as possible, and not as much as I would like.
* Handle callback more often in services
* Cleanup of binder and checker
* More checker cleanup
* Remove TODOs and one more cleanup
* Support parameter-less callback tags
* Remove extra bind call on template type parameters
* Bind template tag containers
Doesn't quite work with typedefs, but that's because it's now stricter,
without the typedef fixes. I'm going to merge with jsdoc/callback and
see how it goes.
* Fix fourslash failures
* Stop pre-binding js type aliases
Next up, stop pre-binding js type parameters
* Further cleanup of delayed js type alias binding
* Stop prebinding template tags too
This gets rid of prebinding entirely
* Remove TODO
* Fix lint
* Finish merge with use-jsdoc-aliases
* Update callback tag baselines
* Rename getTypeParametersForAliasSymbol
The real fix is *probably* to rename Type.aliasTypeArguments to
aliasTypeParameters, but I want to make sure and then put it in a
separate PR.
* JS initializers use original valueDecl, not mutated
target's valueDeclaration is set to the source's if it is not present.
This makes it incorrect to use getJSInitializerSymbol because it relies
on the symbol's valueDeclaration.
This fix just saves the original valueDeclaration before mutating and
uses that.
* Compare merged targetInitializer to target
Instead of the unmerged one
* Add test of stack overflow
* No error for require
Still errors for module and exports, and require's type is now
incorreclty 'any'; I broke module resolution somehow. Needs
investigation.
* module/exports symbols+update isCommonJsRequire
Everything passes the tests but the code can be improved
* Update baselines
* Cleanup
* Update baselines of new tests
* Get rid of exports symbol
It wasn't doing anything anyway.
* Always export typedefs
This actually just required deleting a check in declareModuleMembers
and checking for external AND commonjs modules in a couple of places.
However, while experimenting with this feature, I discovered that even
previously-exported typedefs would only be exported if they came after a
commonjs export node. So I added a commonjs check to the pass in the
parser. It will not catch nested module.exports, but it will catch
top-level assignments.
The new test tests both changes.
* Post-bind typedef instead of pre-checking for commonjs
* Duplicate identifier errors
* Fix class type reference resolution+update baselines
* Move to a type-based check for duplicate identifiers
* Add prettier and fix crash bug
Name resolution would crash when resolving a type name inside a
typedef's property tag.
* Update tsconfig and thefore prettier baseline
If the base type has a property by that name, add it to the list
constructor types to make it as authoritative as special assignments
found in the constructor.
* Make `module.export =` an alias like `export=` is
This breaks a couple of tests for previous workarounds. Fix in upcoming
commits.
* Basically fixes all the breaks, but needs cleanup
* More notes to myself
* Clean up TODOs
* Call mergeSymbolTable and delete export= afterward
instead of basically copying the code myself.
* More cleanup
* Remove unnecessary check in import type checking
* Revert to DIY code.
It is more correct and will go away in a few days.
* Exported class expressions can be used as type
In both JS and TS
* Do not require named class expressions
* Support @template as a class type parameter
Still need to do the following:
1. Correctly get jsdoc host in predicate.
2. Make this work for constructor functions too.
3. Scan rest of codebase for other usages of the type parameters
property that should be calls to getEffectiveTypeParameterDeclarations.
4. Rename tp to something more readable, like typar or ts'.
* Use jsdoc host declaration to find container
* Longer names for type parameters
* Fix renaming operation
* Update fourslash test
* Support @template for JS constructors
* Look for both outer and tag type parameters
* Improve naming to improve code clarity
1. Allow assignment to `exports`.
2. The type of the rhs is not checked against the type of `exports`
since they are aliased declarations.
To support more complex patterns like `exports = c.name = c`, we may
have to treat `c.name` as a declaration. That will be more complicated
than this PR.
* JSDoc:positional matching of destructured params
1. When looking up tags for a parameter whose name is a binding pattern, use
the index of the parameter to get the type.
2. When reporting errors for `@param` tags with no matching parameter
name, do not report the error for tags whose index in the `@param` tag list
matches the index of a parameter whose name is a binding pattern.
* Change to an assert
* Improve comment text
* Combining symbol and removing error done but messy
* Small fix + add new test baselines
All other tests are unchanged
* Union conflicting assignment types+better names
* Add tests and update baselines
* Check commonjs export= from resolveExternalModuleSymbol
* Fix crash in type resolution in JS IIFEs
We recognise IIFEs as JS special assignment initialisers, but not as
containers otherwise. That means that IIFEs will not have a symbol
unless they have an *outside* assignment.
The permanent fix will be to make IIFEs a container, based on the
containership of the value that they return. This fix does not do that;
it just makes type resolution return undefined instead of crashing.
* Comment the IIFE-fix line
* Print js-constructor function type names
Instead of printing them as a type literal, which is scary.
* Use assigned name for functions and classes
That otherwise have no name. This helps quick info for javascript a
*lot*. Typescript mainly benefits when printing the type of class
expressions.
* Improve names of functions in binding elements
Also fix some fourslash baselines
* Type side of import types
* Value side of import types
* Accept library changes
* Refined implementation, more tests
* Allow resolutions to be performed late if the resolution still results in a file already in the build
* Add another test case
* Add some jsdoc usages
* Allow nodebuilder to use import types where appropriate
* Parse & check generic instantiations
* use import types in nodebuilder for typeof module symbols
* Wire up go to definition for import types
* Accept updated type/symbol baselines now that symbols are wired in
* PR feedback
* Fix changes from merge
* Walk back late import handling
* Remove unused diagnostic
* Remove unrelated changes
* Use recursive function over loop
* Emit type arguments
* undo unrelated change
* Test for and support import type nodes in bundled declaration emit
* Add new generated name kind for reused transpiler variables
* Remove error on _super or _newTarget conflict
* Add test with super helper conflict
* Remove error on _this conflict
* Fix lint
* Use flags instead of generated kinds, inline some things
* Accept rename
* Remove trailing whitespace
* Move helper emit into printer, rather than emitter"
* passthru module and target
* New test, accept baselines
* Make members private
* First draft:in js, constructor declaration is preferred
* Add tests
* initializer of null|undefined gives any in JS
Also move this-assignment fixes out of binder. I'm going to put it in
the checker instead.
* In JS, initializer null|undefined: any, []: any[]
* First draft of js prefer-ctor-types overhaul
* Update tests, update baselines
* Improve readability of constructor-type preference
* Cleanup: Remove TODO and duplication
* Add noImplicitAny errors
* Add comment
* Track thisContainer for this-property-assignments in JS
Previously it would update on every block, not just those that could
bind `this`.
In addition, if the constructor symbol still can't be found, then no
binding happens. This is usually OK because people don't add new
properties in methods too often.
* Update additional baselines
* Add lib:dom to new test
* Address PR comments
* Correct new name for saveThisParentContainer
* Add test case and temporarily disable inference
(Inference of class members from this-assignments inside a
prototype-assigned function.)
* Update baselines
* In blocks and source files, bind functions first
* Add tests from other bugs
* Remove temporary failsafe
* Update tests to restore intent and clean up errors
* Restore intent even better
* Restore intent even better x2
* Add missed baselines
* Do not add undefined for this assignments in functions
* Test:constructor functions with --strict
* First draft -- works, but needs a stricter check added
* Update baselines
* Make undefined-skip stricter and more efficient
Symbol-based now instead of syntactic
* Exclude prototype function assignments
* Add explanatory comment
* Correctly parse JSDoc type *=
* Allow `markdown` quoted param names in JSDoc
* Add tests and update baselines
* Get correct span for the type '*'
* Fix whitespace lint
* Add unbracketed type test
* Combine keyof T inferences
* Extract covariant inference derivation into function
* Test:keyof inference lower priority than return inference
for #22376
* Update 'expected' comment in keyofInferenceLowerPriorityThanReturn
* Update comment in test too, not just baselines
* Fix typo
* Move tests
* Fix type when annotated with a JSDoc function type
Previously,
1. A variable annotated with a JSDoc function type would not require all
its parameters to be provided. This should only apply to functions
without a type annotation.
2. A parameter in a function with a JSDoc function type annotation would
still have the type 'any'.
3. Two `var` declarations in a Typescript and Javascript file,
respectively, would error even when they had identical function types.
* Update baselines and add constructor test
* Handle ConstructorType too
* Add test:method sig inside literal type
* Contextually type parameters by parent sig's JSDoc
Instead of a syntactic check in getJSDocTag
* Remove redundant check:isUntypedSignatureInJSFile
* Positive check for value signatures
Instead of excluding type signatures piecemeal.
* Parse JSDoc ...T and T= only at top-level JSDoc
...T and T= should only be legal at the top level of a type, and only in
JSDoc, since at least T= is ambiguous elsewhere. This PR changes parsing
to make that happen. The resulting parse tree is now simpler, allowing
me to get rid of some code I had to add in the checker.
* Extract JSDoc type parsing into its own function
* PR comments:return from parseJSDocType
* jsdoc ?Type adds optionality to parameters
Chrome devtools expects that parameters with type `?T` (or `T?`) add
null to `T` and optionality to the parameter. Previously it only added
null to the type.
Currently the PR does *not* add undefined to the type of
`T`, which is expected by chrome-devtools-frontend, but is inconsistent
with typescript's rules. The implementation achieves this inconsistency by
exploiting the fact that checking the signature adds optionality and
checking the parameter adds `undefined`.
* Update chrome-devtools-frontend baseline
* Add optionality only for jsdoc postfix=
* Skip jsdoc prefix types in isJSDocOptionalParameter
Previously isJSDocOptionalParameter was incorrect for types like
`?number=`, which are optional but have JSDocNullableType as their root
type node.
* No errr on unmatchable `@param` tags
Such as when the initializer is not a function, or when the function
mentions `arguments` in its body.
* Do not require dummy param for JS uses of arguments
1. JS functions that use `arguments` do not require a dummy parameter in
order to get a type for the synthetic `args` parameter if there is an
`@param` with a `...` type.
2.JS functions that use `arguments` and have an `@param` must have a
type that is a `...` type.
* Check for array type instead of syntactic `...`
* Address PR comments
* Update baselines
* Brackets and postfix= in `@param` add undefined
Previously they only added optionality.
Note that, unlike Typescript, when a parameter initializer is specified
in jsdoc, it does not remove undefined in the *body* of the function.
That's because TS will generate initialisation code, but JS won't, so
the author will have to manually write code to remove undefined from the
type.
```js
/** @param {number} [a=101] */
function f(a) {
// a: number | undefined here
if (!a) {
a = 101
}
// a: number here
}
```
Note that we don't check that
1. the initializer value is actually assigned to the parameter.
2. the initializer's type matches the declared type of the parameter.
Pretty much we just parse it and leave it alone.
* Address PR comments
Previously, this would assert:
```ts
exports.undeclared.n = 1;
```
Because undeclared was never declared in any recognised way. Now it no
longer asserts, but does not bind. That's because the full pattern
starts with the line `exports = require('./x')` and assumes that x.js
declares `undeclared`. I am not sure how to bind this. The new test
contains this pattern in case I figure it out.
* Add support for per-file jsx pragmas
* Add error for using jsx factory pragma with fragments
* More tests, use different regex class for pragma capture
* Unify all pragma parsing machinery