Skip to content

Commit f09a0e5

Browse files
Set default types array to []; support "*" wildcard (#63054)
Co-authored-by: Sheetal Nandi <shkamat@microsoft.com>
1 parent 66decdf commit f09a0e5

File tree

1,810 files changed

+4661
-58679
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

1,810 files changed

+4661
-58679
lines changed

src/compiler/checker.ts

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -911,6 +911,7 @@ import {
911911
NodeBuilderFlags,
912912
nodeCanBeDecorated,
913913
NodeCheckFlags,
914+
nodeCoreModules,
914915
NodeFlags,
915916
nodeHasName,
916917
nodeIsMissing,
@@ -1121,6 +1122,7 @@ import {
11211122
UnionType,
11221123
UnionTypeNode,
11231124
UniqueESSymbolType,
1125+
usesWildcardTypes,
11241126
usingSingleLineStringWriter,
11251127
VariableDeclaration,
11261128
VariableDeclarationList,
@@ -4708,9 +4710,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
47084710

47094711
function resolveExternalModuleName(location: Node, moduleReferenceExpression: Expression, ignoreErrors?: boolean, errorMessage?: DiagnosticMessage): Symbol | undefined {
47104712
const isClassic = getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Classic;
4711-
errorMessage ??= isClassic ?
4713+
errorMessage ??= getCannotResolveModuleNameErrorForSpecificModule(moduleReferenceExpression) ?? (isClassic ?
47124714
Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option
4713-
: Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
4715+
: Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations);
47144716
return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : errorMessage, ignoreErrors);
47154717
}
47164718

@@ -27643,27 +27645,29 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
2764327645
case "console":
2764427646
return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
2764527647
case "$":
27646-
return compilerOptions.types
27647-
? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
27648-
: Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery;
27648+
return usesWildcardTypes(compilerOptions)
27649+
? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery
27650+
: Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig;
27651+
case "beforeEach":
2764927652
case "describe":
2765027653
case "suite":
2765127654
case "it":
2765227655
case "test":
27653-
return compilerOptions.types
27654-
? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
27655-
: Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha;
27656+
return usesWildcardTypes(compilerOptions)
27657+
? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha
27658+
: Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig;
2765627659
case "process":
2765727660
case "require":
2765827661
case "Buffer":
2765927662
case "module":
27660-
return compilerOptions.types
27661-
? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
27662-
: Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode;
27663+
case "NodeJS":
27664+
return usesWildcardTypes(compilerOptions)
27665+
? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode
27666+
: Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig;
2766327667
case "Bun":
27664-
return compilerOptions.types
27665-
? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_and_then_add_bun_to_the_types_field_in_your_tsconfig
27666-
: Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun;
27668+
return usesWildcardTypes(compilerOptions)
27669+
? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun
27670+
: Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_and_then_add_bun_to_the_types_field_in_your_tsconfig;
2766727671
case "Map":
2766827672
case "Set":
2766927673
case "Promise":
@@ -27698,6 +27702,20 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
2769827702
}
2769927703
}
2770027704

27705+
function getCannotResolveModuleNameErrorForSpecificModule(moduleName: Expression): DiagnosticMessage | undefined {
27706+
if (moduleName.kind === SyntaxKind.StringLiteral) {
27707+
if (nodeCoreModules.has((moduleName as StringLiteral).text)) {
27708+
if (usesWildcardTypes(compilerOptions)) {
27709+
return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode;
27710+
}
27711+
else {
27712+
return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig;
27713+
}
27714+
}
27715+
}
27716+
return undefined;
27717+
}
27718+
2770127719
function getResolvedSymbol(node: Identifier): Symbol {
2770227720
const links = getNodeLinks(node);
2770327721
if (!links.resolvedSymbol) {

src/compiler/moduleNameResolver.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,15 @@ import {
2626
emptyArray,
2727
endsWith,
2828
ensureTrailingDirectorySeparator,
29+
equateValues,
2930
every,
3031
Extension,
3132
extensionIsTS,
3233
fileExtensionIs,
3334
fileExtensionIsOneOf,
3435
filter,
3536
firstDefined,
37+
flatten,
3638
forEach,
3739
forEachAncestorDirectory,
3840
formatMessage,
@@ -105,6 +107,7 @@ import {
105107
tryExtractTSExtension,
106108
tryGetExtensionFromPath,
107109
tryParsePatterns,
110+
usesWildcardTypes,
108111
Version,
109112
version,
110113
versionMajorMinor,
@@ -803,18 +806,17 @@ export function resolvePackageNameToPackageJson(
803806
* Given a set of options, returns the set of type directive names
804807
* that should be included for this program automatically.
805808
* This list could either come from the config file,
806-
* or from enumerating the types root + initial secondary types lookup location.
809+
* and/or from enumerating the types root + initial secondary types lookup location given "*" compat wildcard.
807810
* More type directives might appear in the program later as a result of loading actual source files;
808811
* this list is only the set of defaults that are implicitly included.
809812
*/
810813
export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[] {
811-
// Use explicit type list from tsconfig.json
812-
if (options.types) {
813-
return options.types;
814+
if (!usesWildcardTypes(options)) {
815+
return options.types ?? [];
814816
}
815817

816818
// Walk the primary type lookup locations
817-
const result: string[] = [];
819+
const wildcardMatches: string[] = [];
818820
if (host.directoryExists && host.getDirectories) {
819821
const typeRoots = getEffectiveTypeRoots(options, host);
820822
if (typeRoots) {
@@ -833,15 +835,18 @@ export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: M
833835
// At this stage, skip results with leading dot.
834836
if (baseFileName.charCodeAt(0) !== CharacterCodes.dot) {
835837
// Return just the type directive names
836-
result.push(baseFileName);
838+
wildcardMatches.push(baseFileName);
837839
}
838840
}
839841
}
840842
}
841843
}
842844
}
843845
}
844-
return result;
846+
847+
// Order potentially matters in program construction, so substitute
848+
// in the wildcard in the position it was specified in the types array
849+
return deduplicate(flatten(options.types.map(t => t === "*" ? wildcardMatches : t)), equateValues);
845850
}
846851

847852
export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache<ResolvedTypeReferenceDirectiveWithFailedLookupLocations>, NonRelativeNameResolutionCache<ResolvedTypeReferenceDirectiveWithFailedLookupLocations>, PackageJsonInfoCache {

src/compiler/programDiagnostics.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import {
5252
removeSuffix,
5353
SourceFile,
5454
TsConfigSourceFile,
55+
usesWildcardTypes,
5556
} from "./_namespaces/ts.js";
5657

5758
interface FileReasonToChainCache {
@@ -400,8 +401,8 @@ export function createProgramDiagnostics(getCompilerOptionsObjectLiteralSyntax:
400401
) :
401402
undefined;
402403
case FileIncludeKind.AutomaticTypeDirectiveFile:
403-
if (!options.types) return undefined;
404-
configFileNode = getOptionsSyntaxByArrayElementValue(getCompilerOptionsObjectLiteralSyntax(), "types", reason.typeReference);
404+
configFileNode = getOptionsSyntaxByArrayElementValue(getCompilerOptionsObjectLiteralSyntax(), "types", usesWildcardTypes(options) ? "*" : reason.typeReference);
405+
405406
message = Diagnostics.File_is_entry_point_of_type_library_specified_here;
406407
break;
407408
case FileIncludeKind.LibFile:

src/compiler/resolutionCache.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ import {
7474
StringLiteralLike,
7575
trace,
7676
updateResolutionField,
77+
usesWildcardTypes,
7778
WatchDirectoryFlags,
7879
} from "./_namespaces/ts.js";
7980

@@ -1667,7 +1668,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD
16671668
*/
16681669
function updateTypeRootsWatch() {
16691670
const options = resolutionHost.getCompilationSettings();
1670-
if (options.types) {
1671+
if (!usesWildcardTypes(options)) {
16711672
// No need to do any watch since resolution cache is going to handle the failed lookups
16721673
// for the types added by this
16731674
closeTypeRootsWatch();

src/compiler/utilities.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8971,6 +8971,14 @@ export function importSyntaxAffectsModuleResolution(options: CompilerOptions): b
89718971
|| getResolvePackageJsonImports(options);
89728972
}
89738973

8974+
/**
8975+
* @internal
8976+
* Returns true if this option's types array includes "*"
8977+
*/
8978+
export function usesWildcardTypes(options: CompilerOptions): options is CompilerOptions & { types: string[]; } {
8979+
return some(options.types, t => t === "*");
8980+
}
8981+
89748982
type CompilerOptionKeys = keyof { [K in keyof CompilerOptions as string extends K ? never : K]: any; };
89758983
function createComputedCompilerOptions<T extends Record<string, CompilerOptionKeys[]>>(
89768984
options: {

src/compiler/watch.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ import {
9797
sourceMapCommentRegExpDontCareLineStart,
9898
sys,
9999
System,
100+
usesWildcardTypes,
100101
WatchCompilerHost,
101102
WatchCompilerHostOfConfigFile,
102103
WatchCompilerHostOfFilesAndCompilerOptions,
@@ -529,7 +530,7 @@ export function fileIncludeReasonToDiagnostics(program: Program, reason: FileInc
529530
options.outFile ? "--outFile" : "--out",
530531
);
531532
case FileIncludeKind.AutomaticTypeDirectiveFile: {
532-
const messageAndArgs: DiagnosticAndArguments = options.types ?
533+
const messageAndArgs: DiagnosticAndArguments = !usesWildcardTypes(options) ?
533534
reason.packageId ?
534535
[Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] :
535536
[Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions, reason.typeReference] :

src/jsTyping/jsTyping.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
some,
2929
toFileNameLowerCase,
3030
TypeAcquisition,
31+
usesWildcardTypes,
3132
Version,
3233
versionMajorMinor,
3334
} from "./_namespaces/ts.js";
@@ -133,7 +134,7 @@ export function discoverTypings(
133134
const exclude = typeAcquisition.exclude || [];
134135

135136
// Directories to search for package.json, bower.json and other typing information
136-
if (!compilerOptions.types) {
137+
if (!compilerOptions.types || usesWildcardTypes(compilerOptions)) {
137138
const possibleSearchDirs = new Set(fileNames.map(getDirectoryPath));
138139
possibleSearchDirs.add(projectRootPath);
139140
possibleSearchDirs.forEach(searchDir => {

src/services/codefixes/fixCannotFindModule.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ const errorCannotFindImplicitJsxImport = Diagnostics.This_JSX_tag_requires_the_m
2727
const errorCodes = [
2828
errorCodeCannotFindModule,
2929
Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code,
30+
Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode.code,
31+
Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig.code,
3032
errorCannotFindImplicitJsxImport,
3133
];
3234
registerCodeFix({
@@ -77,7 +79,11 @@ function tryGetImportedPackageName(sourceFile: SourceFile, pos: number): string
7779
}
7880

7981
function getTypesPackageNameToInstall(packageName: string, host: LanguageServiceHost, diagCode: number): string | undefined {
80-
return diagCode === errorCodeCannotFindModule
81-
? (nodeCoreModules.has(packageName) ? "@types/node" : undefined)
82-
: (host.isKnownTypesPackageName?.(packageName) ? getTypesPackageName(packageName) : undefined);
82+
if (nodeCoreModules.has(packageName)) {
83+
return "@types/node";
84+
}
85+
if (diagCode !== errorCodeCannotFindModule) {
86+
return host.isKnownTypesPackageName?.(packageName) ? getTypesPackageName(packageName) : undefined;
87+
}
88+
return undefined;
8389
}

src/testRunner/unittests/tsbuild/moduleResolution.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,13 +78,13 @@ describe("unittests:: tsbuild:: moduleResolution:: handles the modules and optio
7878
TestServerHost.createWatchedSystem({
7979
"/home/src/workspaces/project/packages/pkg1_index.ts": `export const theNum: TheNum = "type1";`,
8080
"/home/src/workspaces/project/packages/pkg1.tsconfig.json": jsonToReadableText({
81-
compilerOptions: { composite: true, typeRoots: ["./typeroot1"] },
81+
compilerOptions: { composite: true, typeRoots: ["./typeroot1"], types: ["*"] },
8282
files: ["./pkg1_index.ts"],
8383
}),
8484
"/home/src/workspaces/project/packages/typeroot1/sometype/index.d.ts": dedent`declare type TheNum = "type1";`,
8585
"/home/src/workspaces/project/packages/pkg2_index.ts": `export const theNum: TheNum2 = "type2";`,
8686
"/home/src/workspaces/project/packages/pkg2.tsconfig.json": jsonToReadableText({
87-
compilerOptions: { composite: true, typeRoots: ["./typeroot2"] },
87+
compilerOptions: { composite: true, typeRoots: ["./typeroot2"], types: ["*"] },
8888
files: ["./pkg2_index.ts"],
8989
}),
9090
"/home/src/workspaces/project/packages/typeroot2/sometype/index.d.ts": dedent`declare type TheNum2 = "type2";`,
@@ -163,7 +163,7 @@ describe("unittests:: tsbuild:: moduleResolution:: impliedNodeFormat differs bet
163163
TestServerHost.createWatchedSystem({
164164
"/home/src/workspaces/project/a/src/index.ts": "",
165165
"/home/src/workspaces/project/a/tsconfig.json": jsonToReadableText({
166-
compilerOptions: { strict: true },
166+
compilerOptions: { strict: true, types: ["*"] },
167167
}),
168168
"/home/src/workspaces/project/b/src/index.ts": dedent`
169169
import pg from "pg";

src/testRunner/unittests/tsc/incremental.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ declare global {
188188
"/home/src/workspaces/project/node_modules/react/jsx-runtime.js": "export {}", // js needs to be present so there's a resolution result
189189
"/home/src/workspaces/project/node_modules/@types/react/index.d.ts": getJsxLibraryContent(), // doesn't contain a jsx-runtime definition
190190
"/home/src/workspaces/project/src/index.tsx": `export const App = () => <div propA={true}></div>;`,
191-
"/home/src/workspaces/project/tsconfig.json": jsonToReadableText({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" } }),
191+
"/home/src/workspaces/project/tsconfig.json": jsonToReadableText({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react", types: ["react"] } }),
192192
}),
193193
commandLineArgs: ts.emptyArray,
194194
});
@@ -201,7 +201,7 @@ declare global {
201201
"/home/src/workspaces/project/node_modules/react/jsx-runtime.js": "export {}", // js needs to be present so there's a resolution result
202202
"/home/src/workspaces/project/node_modules/@types/react/index.d.ts": getJsxLibraryContent(), // doesn't contain a jsx-runtime definition
203203
"/home/src/workspaces/project/src/index.tsx": `export const App = () => <div propA={true}></div>;`,
204-
"/home/src/workspaces/project/tsconfig.json": jsonToReadableText({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" } }),
204+
"/home/src/workspaces/project/tsconfig.json": jsonToReadableText({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react", types: ["react"] } }),
205205
}),
206206
commandLineArgs: ["--strict"],
207207
});

0 commit comments

Comments
 (0)