Skip to content

Finish applying no-object-literal-type-assertion lint rule #18218

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

Closed
wants to merge 7 commits into from
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
2 changes: 2 additions & 0 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1037,6 +1037,7 @@ namespace ts {

function getNodeLinks(node: Node): NodeLinks {
const nodeId = getNodeId(node);
// tslint:disable-next-line no-object-literal-type-assertion TODO: GH#18217
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 } as NodeLinks);
}

Expand Down Expand Up @@ -2517,6 +2518,7 @@ namespace ts {
if (lookupTable && exportNode) {
lookupTable.set(id, {
specifierText: getTextOfNode(exportNode.moduleSpecifier!)
// tslint:disable-next-line no-object-literal-type-assertion (TODO: GH#18217)
} as ExportCollisionTracker);
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/compiler/commandLineParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -971,7 +971,7 @@ namespace ts {
[unknownOptionDiagnostic, optionTypeMismatchDiagnostic]: ParseCommandLineWorkerDiagnostics,
commandLine: ReadonlyArray<string>,
readFile?: (path: string) => string | undefined) {
const options = {} as OptionsBase;
const options: OptionsBase = {};
const fileNames: string[] = [];
const errors: Diagnostic[] = [];

Expand Down Expand Up @@ -1335,6 +1335,7 @@ namespace ts {
*/
export function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile {
const textOrDiagnostic = tryReadFile(fileName, readFile);
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
Copy link
Contributor

Choose a reason for hiding this comment

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

we should change the return type for this function instead.

Copy link
Author

@ghost ghost Nov 3, 2017

Choose a reason for hiding this comment

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

To { parseDiagnostics: Diagnostic[] }? That exposes errors in its uses because we seem to assume we get the full source file.

Copy link
Contributor

Choose a reason for hiding this comment

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

with optional members for fileName and extendedSourceFiles.. not sure if we need other things as well.

Copy link
Contributor

Choose a reason for hiding this comment

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

that might end up touching many places though..

return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : <TsConfigSourceFile>{ parseDiagnostics: [textOrDiagnostic] };
}

Expand Down
5 changes: 5 additions & 0 deletions src/compiler/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2558,6 +2558,7 @@ namespace ts {
/* @internal */
export function createEndOfDeclarationMarker(original: Node) {
const node = <EndOfDeclarationMarker>createSynthesizedNode(SyntaxKind.EndOfDeclarationMarker);
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
node.emitNode = {} as EmitNode;
node.original = original;
return node;
Expand All @@ -2570,6 +2571,7 @@ namespace ts {
/* @internal */
export function createMergeDeclarationMarker(original: Node) {
const node = <MergeDeclarationMarker>createSynthesizedNode(SyntaxKind.MergeDeclarationMarker);
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
node.emitNode = {} as EmitNode;
node.original = original;
return node;
Expand Down Expand Up @@ -2824,13 +2826,15 @@ namespace ts {
// parse tree node we are annotating. This allows us to clean them up after
// all transformations have completed.
if (node.kind === SyntaxKind.SourceFile) {
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
return node.emitNode = { annotatedNodes: [node] } as EmitNode;
}

const sourceFile = getSourceFileOfNode(node);
getOrCreateEmitNode(sourceFile).annotatedNodes!.push(node);
}

// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
node.emitNode = {} as EmitNode;
}

Expand Down Expand Up @@ -3096,6 +3100,7 @@ namespace ts {
helpers,
startsOnNewLine,
} = sourceEmitNode;
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
if (!destEmitNode) destEmitNode = {} as EmitNode;
// We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
if (leadingComments) destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments);
Expand Down
3 changes: 3 additions & 0 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7877,9 +7877,11 @@ namespace ts {
}
}
}
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
pragmas.push({ name, args: { arguments: argument, range } } as PragmaPseudoMapEntry);
}
else {
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
pragmas.push({ name, args: { arguments: {}, range } } as PragmaPseudoMapEntry);
}
return;
Expand Down Expand Up @@ -7909,6 +7911,7 @@ namespace ts {
const args = match[2]; // Split on spaces and match up positionally with definition
const argument = getNamedPragmaArguments(pragma, args);
if (argument === "fail") return; // Missing required argument, fail to parse it
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
pragmas.push({ name, args: { arguments: argument, range } } as PragmaPseudoMapEntry);
return;
}
Expand Down
1 change: 1 addition & 0 deletions src/compiler/transformers/es2017.ts
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,7 @@ namespace ts {
);

// Mark this node as originally an async function
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
(generatorFunc.emitNode || (generatorFunc.emitNode = {} as EmitNode)).flags |= EmitFlags.AsyncFunctionBody | EmitFlags.ReuseTempVariableScope;

return createCall(
Expand Down
1 change: 1 addition & 0 deletions src/compiler/transformers/esnext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -995,6 +995,7 @@ namespace ts {
context.requestEmitHelper(asyncGeneratorHelper);

// Mark this node as originally an async function
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
(generatorFunc.emitNode || (generatorFunc.emitNode = {} as EmitNode)).flags |= EmitFlags.AsyncFunctionBody;

return createCall(
Expand Down
4 changes: 2 additions & 2 deletions src/compiler/tsbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ namespace ts {
}

function getCompilerOptionsOfBuildOptions(buildOptions: BuildOptions): CompilerOptions {
const result = {} as CompilerOptions;
const result: CompilerOptions = {};
commonOptionsWithBuild.forEach(option => {
result[option.name] = buildOptions[option.name];
});
Expand Down Expand Up @@ -1119,7 +1119,7 @@ namespace ts {
host.setModifiedTime(file, now);
}

projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus);
projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
}

function getFilesToClean(): string[] {
Expand Down
5 changes: 3 additions & 2 deletions src/harness/documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ namespace documents {
}

public asTestFile() {
const fileOptions: Record<string, string> = {};
this.meta.forEach((value, key) => { fileOptions[key] = value; });
return this._testFile || (this._testFile = {
unitName: this.file,
content: this.text,
fileOptions: Array.from(this.meta)
.reduce((obj, [key, value]) => (obj[key] = value, obj), {} as Record<string, string>)
fileOptions,
});
}
}
Expand Down
1 change: 1 addition & 0 deletions src/harness/fourslash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ namespace FourSlash {
"getReferencesAtPosition",
"getDocumentHighlights",
];
// tslint:disable-next-line no-object-literal-type-assertion
const proxy = {} as ts.LanguageService;
for (const k in ls) {
const key = k as keyof typeof ls;
Expand Down
7 changes: 4 additions & 3 deletions src/harness/vfs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -846,8 +846,8 @@ namespace vfs {
private _mknod(dev: number, type: typeof S_IFREG, mode: number, time?: number): FileInode;
private _mknod(dev: number, type: typeof S_IFDIR, mode: number, time?: number): DirectoryInode;
private _mknod(dev: number, type: typeof S_IFLNK, mode: number, time?: number): SymlinkInode;
private _mknod(dev: number, type: number, mode: number, time = this.time()) {
return <Inode>{
private _mknod(dev: number, type: number, mode: number, time = this.time()): Inode {
return {
dev,
ino: ++inoCount,
mode: (mode & ~S_IFMT & ~0o022 & 0o7777) | (type & S_IFMT),
Expand Down Expand Up @@ -940,7 +940,7 @@ namespace vfs {

let shadow = shadows.get(root.ino);
if (!shadow) {
shadow = <Inode>{
const inode: Inode = {
dev: root.dev,
ino: root.ino,
mode: root.mode,
Expand All @@ -951,6 +951,7 @@ namespace vfs {
nlink: root.nlink,
shadowRoot: root
};
shadow = inode;

if (isSymlink(root)) (<SymlinkInode>shadow).symlink = root.symlink;
shadows.set(shadow.ino, shadow);
Expand Down
6 changes: 4 additions & 2 deletions src/server/editorServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1695,6 +1695,7 @@ namespace ts.server {

const result = parseJsonText(configFilename, configFileContent);
if (!result.endOfFileToken) {
// tslint:disable-next-line no-object-literal-type-assertion (TODO: GH#18217)
result.endOfFileToken = <EndOfFileToken>{ kind: SyntaxKind.EndOfFileToken };
}
const configFileErrors = result.parseDiagnostics as Diagnostic[];
Expand Down Expand Up @@ -1849,10 +1850,11 @@ namespace ts.server {
const diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics();
diagnostics.push(...project.getAllProjectErrors());

this.eventHandler(<ConfigFileDiagEvent>{
const event: ConfigFileDiagEvent = {
eventName: ConfigFileDiagEvent,
data: { configFileName: project.getConfigFilePath(), diagnostics, triggerFile }
});
};
this.eventHandler(event);
}

private getOrCreateInferredProjectForProjectRootPathIfEnabled(info: ScriptInfo, projectRootPath: NormalizedPath | undefined): InferredProject | undefined {
Expand Down
1 change: 1 addition & 0 deletions src/server/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1105,6 +1105,7 @@ namespace ts.server {
// Provide global: true so plugins can detect why they can't find their config
this.projectService.logger.info(`Loading global plugin ${globalPluginName}`);

// tslint:disable-next-line no-object-literal-type-assertion (TODO: GH#18217)
this.enablePlugin({ name: globalPluginName, global: true } as PluginImport, searchPaths, pluginConfigOverrides);
}
}
Expand Down
16 changes: 8 additions & 8 deletions src/server/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -896,18 +896,18 @@ namespace ts.server {
}

private convertToDiagnosticsWithLinePosition(diagnostics: ReadonlyArray<Diagnostic>, scriptInfo: ScriptInfo | undefined): protocol.DiagnosticWithLinePosition[] {
return diagnostics.map(d => <protocol.DiagnosticWithLinePosition>{
return diagnostics.map((d): protocol.DiagnosticWithLinePosition => ({
message: flattenDiagnosticMessageText(d.messageText, this.host.newLine),
start: d.start,
length: d.length,
start: d.start!, // TODO: GH#18217
length: d.length!,
category: diagnosticCategoryName(d),
code: d.code,
source: d.source,
startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start!), // TODO: GH#18217
endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start! + d.length!),
["sour" + "ce"]: d.source, // TODO: GH#18217
startLocation: (scriptInfo && scriptInfo.positionToLineOffset(d.start!))!, // TODO: GH#18217
endLocation: (scriptInfo && scriptInfo.positionToLineOffset(d.start! + d.length!))!,
reportsUnnecessary: d.reportsUnnecessary,
relatedInformation: map(d.relatedInformation, formatRelatedInformation),
});
}));
}

private getDiagnosticsWorker(
Expand Down Expand Up @@ -2404,7 +2404,7 @@ namespace ts.server {
}
}

public executeCommand(request: protocol.Request): HandlerResponse {
public executeCommand<T extends protocol.Request>(request: T): HandlerResponse {
const handler = this.handlers.get(request.command);
if (handler) {
return this.executeWithRequestId(request.seq, () => handler(request));
Expand Down
4 changes: 2 additions & 2 deletions src/services/sourcemaps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,13 @@ namespace ts {
if (!host.fileExists || !host.readFile || !host.fileExists(path)) return;
// And failing that, check the disk
const text = host.readFile(path)!; // TODO: GH#18217
const file = {
const file: SourceFileLike = {
text,
lineMap: undefined,
getLineAndCharacterOfPosition(pos: number) {
return computeLineAndCharacterOfPosition(getLineStarts(this), pos);
}
} as SourceFileLike;
};
cached.set(path, file);
return file;
}
Expand Down
6 changes: 4 additions & 2 deletions src/testRunner/parallel/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,10 +348,12 @@ namespace Harness.Parallel.Host {
}
worker.currentTasks = taskList;
if (taskList.length === 1) {
worker.process.send({ type: "test", payload: taskList[0] } as ParallelHostMessage); // TODO: GH#18217
// tslint:disable-next-line no-object-literal-type-assertion (TODO: GH#18217)
worker.process.send({ type: "test", payload: taskList[0] } as ParallelHostMessage);
}
else {
worker.process.send({ type: "batch", payload: taskList } as ParallelHostMessage); // TODO: GH#18217
// tslint:disable-next-line no-object-literal-type-assertion (TODO: GH#18217)
worker.process.send({ type: "batch", payload: taskList } as ParallelHostMessage);
}
}
}
Expand Down
9 changes: 5 additions & 4 deletions src/testRunner/unittests/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,9 @@ namespace ts.server {
}
};
session.onMessage(JSON.stringify(setOptionsRequest));
assert.deepEqual(
assert.deepEqual<CompilerOptions>(
session.getProjectService().getCompilerOptionsForInferredProjects(),
<CompilerOptions>{
{
module: ModuleKind.System,
target: ScriptTarget.ES5,
jsx: JsxEmit.React,
Expand Down Expand Up @@ -316,14 +316,15 @@ namespace ts.server {

session.onMessage(JSON.stringify(req));

expect(lastSent).to.deep.equal(<protocol.ConfigureResponse>{
const response: protocol.ConfigureResponse = {
command: CommandNames.Configure,
type: "response",
success: true,
request_seq: 0,
seq: 0,
body: undefined
});
};
assert.deepEqual<protocol.Message>(lastSent, response);
});
});

Expand Down
12 changes: 8 additions & 4 deletions src/testRunner/unittests/tsconfigParsing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,22 @@ namespace ts {

function getParsedCommandJson(jsonText: string, configFileName: string, basePath: string, allFileList: string[]) {
const parsed = parseConfigFileTextToJson(configFileName, jsonText);
const files = allFileList.reduce((files, value) => (files[value] = "", files), {} as vfs.FileSet);
const host: ParseConfigHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ false, { cwd: basePath, files: { "/": {}, ...files } }));
const host: ParseConfigHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ false, { cwd: basePath, files: { "/": {}, ...filesToFileSet(allFileList) } }));
return parseJsonConfigFileContent(parsed.config, host, basePath, /*existingOptions*/ undefined, configFileName);
}

function getParsedCommandJsonNode(jsonText: string, configFileName: string, basePath: string, allFileList: string[]) {
const parsed = parseJsonText(configFileName, jsonText);
const files = allFileList.reduce((files, value) => (files[value] = "", files), {} as vfs.FileSet);
const host: ParseConfigHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ false, { cwd: basePath, files: { "/": {}, ...files } }));
const host: ParseConfigHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ false, { cwd: basePath, files: { "/": {}, ...filesToFileSet(allFileList) } }));
return parseJsonSourceFileConfigFileContent(parsed, host, basePath, /*existingOptions*/ undefined, configFileName);
}

function filesToFileSet(allFileList: ReadonlyArray<string>): vfs.FileSet {
const files: vfs.FileSet = {};
for (const file of allFileList) { files[file] = ""; }
return files;
}

function assertParseFileList(jsonText: string, configFileName: string, basePath: string, allFileList: string[], expectedFileList: string[]) {
{
const parsed = getParsedCommandJson(jsonText, configFileName, basePath, allFileList);
Expand Down
2 changes: 2 additions & 0 deletions src/testRunner/unittests/tsserverProjectSystem.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// tslint:disable no-object-literal-type-assertion (TODO: GH#18217)

namespace ts.projectSystem {
import TI = server.typingsInstaller;
import protocol = server.protocol;
Expand Down
1 change: 1 addition & 0 deletions src/typingsInstallerCore/typingsInstaller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ namespace ts.server.typingsInstaller {
this.installRunCount++;

// send progress event
// tslint:disable-next-line no-object-literal-type-assertion (TODO:GH#18217)
this.sendResponse(<BeginInstallTypes>{
kind: EventBeginInstallTypes,
eventId: requestId,
Expand Down
2 changes: 1 addition & 1 deletion tests/baselines/reference/api/tsserverlibrary.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8919,7 +8919,7 @@ declare namespace ts.server {
private setCurrentRequest;
private resetCurrentRequest;
executeWithRequestId<T>(requestId: number, f: () => T): T;
executeCommand(request: protocol.Request): HandlerResponse;
executeCommand<T extends protocol.Request>(request: T): HandlerResponse;
onMessage(message: string): void;
private getFormatOptions;
private getPreferences;
Expand Down
1 change: 0 additions & 1 deletion tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@
"no-debugger": false,
"no-empty-interface": false,
"no-eval": false,
"no-object-literal-type-assertion": false,
"no-shadowed-variable": false,
"no-submodule-imports": false,
"no-var-requires": false,
Expand Down