From d9b287df484f1a440be848041412c02848fbddb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josh=20Goldberg=20=E2=9C=A8?= Date: Mon, 25 Aug 2025 16:21:19 -0400 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=A4=96=20Merge=20PR=20#73082=20[sizzl?= =?UTF-8?q?e]=20fix:=20add=20empty=20DOM=20global=20interfaces=20for=20non?= =?UTF-8?q?-DOM=20users=20by=20@JoshuaKGoldberg?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- types/sizzle/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/sizzle/index.d.ts b/types/sizzle/index.d.ts index e5d3eb0c7c8dce..d03be8b04b2258 100644 --- a/types/sizzle/index.d.ts +++ b/types/sizzle/index.d.ts @@ -3,6 +3,12 @@ export as namespace Sizzle; declare const Sizzle: SizzleStatic; export = Sizzle; +// For users who don't have "dom" types +// See: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/73082 +type Element = typeof globalThis extends { Element: { new(): infer T } } ? T : never; +type Document = typeof globalThis extends { Document: { new(): infer T } } ? T : never; +type DocumentFragment = typeof globalThis extends { DocumentFragment: { new(): infer T } } ? T : never; + interface SizzleStatic { selectors: Sizzle.Selectors; >( From b46e1e10611afce7d8e449251f68f1f7cd7128c2 Mon Sep 17 00:00:00 2001 From: "SATO, Yoshiyuki" Date: Tue, 26 Aug 2025 07:29:03 +0900 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A4=96=20Merge=20PR=20#73466=20fix(go?= =?UTF-8?q?ogle-apps-script):=20allow=20nullable=20return=20types=20for=20?= =?UTF-8?q?APIs=20that=20return=20null=20by=20@yoshi389111?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../google-apps-script.xml-service.d.ts | 72 +++--- types/google-apps-script/package.json | 2 +- .../test/google-apps-script-tests.ts | 244 ++++++++++++++---- types/google-apps-script/tsconfig.json | 2 +- 4 files changed, 230 insertions(+), 90 deletions(-) diff --git a/types/google-apps-script/google-apps-script.xml-service.d.ts b/types/google-apps-script/google-apps-script.xml-service.d.ts index 9f1e26119d6911..082dfcf41b68fc 100644 --- a/types/google-apps-script/google-apps-script.xml-service.d.ts +++ b/types/google-apps-script/google-apps-script.xml-service.d.ts @@ -45,7 +45,7 @@ declare namespace GoogleAppsScript { interface Cdata extends Content { append(text: string): Text; detach(): Content; - getParentElement(): Element; + getParentElement(): Element | null; getText(): string; getValue(): string; setText(text: string): Text; @@ -55,7 +55,7 @@ declare namespace GoogleAppsScript { */ interface Comment extends Content { detach(): Content; - getParentElement(): Element; + getParentElement(): Element | null; getText(): string; getValue(): string; setText(text: string): Comment; @@ -81,15 +81,15 @@ declare namespace GoogleAppsScript { * TextA representation of an XML Text node. */ interface Content { - asCdata(): Cdata; - asComment(): Comment; - asDocType(): DocType; - asElement(): Element; - asEntityRef(): EntityRef; - asProcessingInstruction(): ProcessingInstruction; - asText(): Text; + asCdata(): Cdata | null; + asComment(): Comment | null; + asDocType(): DocType | null; + asElement(): Element | null; + asEntityRef(): EntityRef | null; + asProcessingInstruction(): ProcessingInstruction | null; + asText(): Text | null; detach(): Content; - getParentElement(): Element; + getParentElement(): Element | null; getType(): ContentType; getValue(): string; } @@ -111,10 +111,10 @@ declare namespace GoogleAppsScript { interface DocType extends Content { detach(): Content; getElementName(): string; - getInternalSubset(): string; - getParentElement(): Element; - getPublicId(): string; - getSystemId(): string; + getInternalSubset(): string | null; + getParentElement(): Element | null; + getPublicId(): string | null; + getSystemId(): string | null; getValue(): string; setElementName(name: string): DocType; setInternalSubset(data: string): DocType; @@ -128,17 +128,17 @@ declare namespace GoogleAppsScript { addContent(content: Content): Document; addContent(index: Integer, content: Content): Document; cloneContent(): Content[]; - detachRootElement(): Element; + detachRootElement(): Element | null; getAllContent(): Content[]; - getContent(index: Integer): Content; + getContent(index: Integer): Content | null; getContentSize(): Integer; getDescendants(): Content[]; - getDocType(): DocType; - getRootElement(): Element; + getDocType(): DocType | null; + getRootElement(): Element | null; hasRootElement(): boolean; removeContent(): Content[]; removeContent(content: Content): boolean; - removeContent(index: Integer): Content; + removeContent(index: Integer): Content | null; setDocType(docType: DocType): Document; setRootElement(element: Element): Document; } @@ -169,24 +169,24 @@ declare namespace GoogleAppsScript { cloneContent(): Content[]; detach(): Content; getAllContent(): Content[]; - getAttribute(name: string): Attribute; - getAttribute(name: string, namespace: Namespace): Attribute; + getAttribute(name: string): Attribute | null; + getAttribute(name: string, namespace: Namespace): Attribute | null; getAttributes(): Attribute[]; - getChild(name: string): Element; - getChild(name: string, namespace: Namespace): Element; - getChildText(name: string): string; - getChildText(name: string, namespace: Namespace): string; + getChild(name: string): Element | null; + getChild(name: string, namespace: Namespace): Element | null; + getChildText(name: string): string | null; + getChildText(name: string, namespace: Namespace): string | null; getChildren(): Element[]; getChildren(name: string): Element[]; getChildren(name: string, namespace: Namespace): Element[]; - getContent(index: Integer): Content; + getContent(index: Integer): Content | null; getContentSize(): Integer; getDescendants(): Content[]; - getDocument(): Document; + getDocument(): Document | null; getName(): string; getNamespace(): Namespace; - getNamespace(prefix: string): Namespace; - getParentElement(): Element; + getNamespace(prefix: string): Namespace | null; + getParentElement(): Element | null; getQualifiedName(): string; getText(): string; getValue(): string; @@ -197,7 +197,7 @@ declare namespace GoogleAppsScript { removeAttribute(attributeName: string, namespace: Namespace): boolean; removeContent(): Content[]; removeContent(content: Content): boolean; - removeContent(index: Integer): Content; + removeContent(index: Integer): Content | null; setAttribute(attribute: Attribute): Element; setAttribute(name: string, value: string): Element; setAttribute(name: string, value: string, namespace: Namespace): Element; @@ -211,9 +211,9 @@ declare namespace GoogleAppsScript { interface EntityRef extends Content { detach(): Content; getName(): string; - getParentElement(): Element; - getPublicId(): string; - getSystemId(): string; + getParentElement(): Element | null; + getPublicId(): string | null; + getSystemId(): string | null; getValue(): string; setName(name: string): EntityRef; setPublicId(id: string): EntityRef; @@ -237,7 +237,7 @@ declare namespace GoogleAppsScript { format(document: Document): string; format(element: Element): string; setEncoding(encoding: string): Format; - setIndent(indent: string): Format; + setIndent(indent: string | null): Format; setLineSeparator(separator: string): Format; setOmitDeclaration(omitDeclaration: boolean): Format; setOmitEncoding(omitEncoding: boolean): Format; @@ -255,7 +255,7 @@ declare namespace GoogleAppsScript { interface ProcessingInstruction extends Content { detach(): Content; getData(): string; - getParentElement(): Element; + getParentElement(): Element | null; getTarget(): string; getValue(): string; } @@ -265,7 +265,7 @@ declare namespace GoogleAppsScript { interface Text extends Content { append(text: string): Text; detach(): Content; - getParentElement(): Element; + getParentElement(): Element | null; getText(): string; getValue(): string; setText(text: string): Text; diff --git a/types/google-apps-script/package.json b/types/google-apps-script/package.json index c7c720addf2444..f4e62d548f4a48 100644 --- a/types/google-apps-script/package.json +++ b/types/google-apps-script/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "@types/google-apps-script", - "version": "1.0.9999", + "version": "2.0.9999", "projects": [ "https://developers.google.com/apps-script/" ], diff --git a/types/google-apps-script/test/google-apps-script-tests.ts b/types/google-apps-script/test/google-apps-script-tests.ts index ce4d86c51de74a..5fd543fc572ef1 100644 --- a/types/google-apps-script/test/google-apps-script-tests.ts +++ b/types/google-apps-script/test/google-apps-script-tests.ts @@ -68,10 +68,11 @@ function testOAuthScopes() { } // Advanced Services -Slides.Presentations.Pages.getThumbnail("presentationId", "pageId"); +Slides.Presentations?.Pages?.getThumbnail("presentationId", "pageId"); // Calendar (Advanced service) const createEvent = (): GoogleAppsScript.Calendar.Schema.Event => { + if (!Calendar.Events) throw new Error("Calendar.Events is not available"); const calendarId = "primary"; const start = new Date(); const end = new Date(); @@ -100,6 +101,7 @@ const createEvent = (): GoogleAppsScript.Calendar.Schema.Event => { // Calendar Working Locations (Advanced Service) const createWorkingLocationEvent = (): void => { + if (!Calendar.Events) return; const calendarId = "primary"; const start = new Date(); const end = new Date(); @@ -135,19 +137,19 @@ const createWorkingLocationEvent = (): void => { // Admin Directory (Advanced service) const listAllUsers = () => { - let pageToken: string; - let page: GoogleAppsScript.AdminDirectory.Schema.Users; + let pageToken: string | undefined = undefined; + if (!AdminDirectory.Users) return; do { - page = AdminDirectory.Users.list({ + const page: GoogleAppsScript.AdminDirectory.Schema.Users = AdminDirectory.Users.list({ domain: "example.com", orderBy: "givenName", maxResults: 100, pageToken: pageToken, }); - const users: GoogleAppsScript.AdminDirectory.Schema.User[] = page.users; + const users = page.users; if (users) { for (const user of users) { - Logger.log("%s (%s)", user.name.fullName, user.primaryEmail); + Logger.log("%s (%s)", user.name?.fullName, user.primaryEmail); } } else { Logger.log("No users found."); @@ -158,24 +160,24 @@ const listAllUsers = () => { // Admin Directory - User Organization const listAllUserOrganizations = () => { - let pageToken: string; - let page: GoogleAppsScript.AdminDirectory.Schema.Users; + let pageToken: string | undefined = undefined; + if (!AdminDirectory.Users) return; do { - page = AdminDirectory.Users.list({ + const page: GoogleAppsScript.AdminDirectory.Schema.Users = AdminDirectory.Users.list({ domain: "example.com", orderBy: "givenName", maxResults: 100, pageToken: pageToken, viewType: "domain_public", }); - const users: GoogleAppsScript.AdminDirectory.Schema.User[] = page.users; + const users = page.users; if (users) { for (const user of users) { Logger.log( "%s: %s - %s)", - user.name.fullName, - user.organizations[0].location, - user.organizations[0].department, + user.name?.fullName, + user.organizations?.[0].location, + user.organizations?.[0].department, ); } } else { @@ -295,29 +297,33 @@ const themeTextStyle = SpreadsheetApp.newTextStyle().setForegroundColorObject(co const nullTextStyle = SpreadsheetApp.newTextStyle().build(); // Null Color Test -// $ExpectType Color +// $ExpectType Color | null const nullColorObj = nullTextStyle.getForegroundColorObject(); Logger.log(nullColorObj); // null // RgbColor Test -// $ExpectType Color +// $ExpectType Color | null const rgbColorObj = rgbTextStyle.getForegroundColorObject(); -Logger.log(rgbColorObj); // Color -Logger.log(rgbColorObj.getColorType()); // RGB -Logger.log(rgbColorObj.asRgbColor().asHexString()); // #ff0000 -Logger.log(rgbColorObj.asRgbColor().getBlue()); // 0 -Logger.log(rgbColorObj.asRgbColor().getGreen()); // 0 -Logger.log(rgbColorObj.asRgbColor().getRed()); // 255 +if (rgbColorObj) { + Logger.log(rgbColorObj); // Color + Logger.log(rgbColorObj.getColorType()); // RGB + Logger.log(rgbColorObj.asRgbColor().asHexString()); // #ff0000 + Logger.log(rgbColorObj.asRgbColor().getBlue()); // 0 + Logger.log(rgbColorObj.asRgbColor().getGreen()); // 0 + Logger.log(rgbColorObj.asRgbColor().getRed()); // 255 +} // ThemeColor Test -// $ExpectType Color +// $ExpectType Color | null const themeColorObj = themeTextStyle.getForegroundColorObject(); -Logger.log(themeColorObj); // Color -Logger.log(themeColorObj.getColorType()); // THEME -Logger.log(themeColorObj.asThemeColor().getThemeColorType()); // ACCENT1 +if (themeColorObj) { + Logger.log(themeColorObj); // Color + Logger.log(themeColorObj.getColorType()); // THEME + Logger.log(themeColorObj.asThemeColor().getThemeColorType()); // ACCENT1 +} -const tableCell = DocumentApp.create("").getCursor().getElement().asTableCell(); -tableCell.getParentRow().getChildIndex(tableCell); +const tableCell = DocumentApp.create("").getCursor()?.getElement().asTableCell(); +tableCell?.getParentRow().getChildIndex(tableCell); XmlService.createElement("") .addContent(XmlService.createCdata("")) @@ -325,6 +331,118 @@ XmlService.createElement("") .addContent(XmlService.createDocType("")) .addContent(XmlService.createText("")); +// https://developers.google.com/apps-script/reference/xml-service +const parseXml = () => { + const xml = "" + + " " + + " title 1cat1cat2" + + " title 2cat2" + + " title 3cat1cat3" + + " title 4" + + " " + + ""; + const document = XmlService.parse(xml); // $ExpectType Document + const root = document.getRootElement(); // $ExpectType Element | null + + const channel = root?.getChild("channel"); + const items = channel?.getChildren("item") ?? []; + items.forEach(item => { + const title = item.getChild("title")?.getText(); + const categories = item.getChildren("category"); + const labels = categories.map(category => category.getText()); + console.log("%s (%s)", title, labels.join(", ")); + }); +}; + +// https://developers.google.com/apps-script/reference/xml-service +const createXml = () => { + const root = XmlService.createElement("threads"); + const threads = [ + { messageCount: 1, isUnread: true, subject: "subject 1" }, + { messageCount: 10, isUnread: true, subject: "subject 2" }, + { messageCount: 3, isUnread: false, subject: "subject 3" }, + ]; + threads.forEach(thread => { + const child = XmlService.createElement("thread") + .setAttribute("messageCount", String(thread.messageCount)) + .setAttribute("isUnread", String(thread.isUnread)) + .setText(thread.subject); + root.addContent(child); + }); + const document = XmlService.createDocument(root); + const xml = XmlService.getPrettyFormat().format(document); + console.log(xml); +}; + +const testXmlService = () => { + // https://developers.google.com/apps-script/reference/xml-service/cdata + const cdata = XmlService.createCdata("cdata"); // $ExpectType Cdata + cdata.getParentElement(); // $ExpectType Element | null + + // https://developers.google.com/apps-script/reference/xml-service/comment + const comment = XmlService.createComment("comment"); // $ExpectType Comment + comment.getParentElement(); // $ExpectType Element | null + + // https://developers.google.com/apps-script/reference/xml-service/content + const content = XmlService.createComment("").detach(); + content.asCdata(); // $ExpectType Cdata | null + content.asComment(); // $ExpectType Comment | null + content.asDocType(); // $ExpectType DocType | null + content.asElement(); // $ExpectType Element | null + content.asEntityRef(); // $ExpectType EntityRef | null + content.asProcessingInstruction(); // $ExpectType ProcessingInstruction | null + content.asText(); // $ExpectType Text | null + content.getParentElement(); // $ExpectType Element | null + + // https://developers.google.com/apps-script/reference/xml-service/doc-type + const docType = XmlService.createDocType("html"); // $ExpectType DocType + docType.getInternalSubset(); // $ExpectType string | null + docType.getParentElement(); // $ExpectType Element | null + docType.getPublicId(); // $ExpectType string | null + docType.getSystemId(); // $ExpectType string | null + + // https://developers.google.com/apps-script/reference/xml-service/document + const doc = XmlService.createDocument(); // $ExpectType Document + doc.detachRootElement(); // $ExpectType Element | null + doc.getContent(0); // $ExpectType Content | null + doc.getDocType(); // $ExpectType DocType | null + doc.getRootElement(); // $ExpectType Element | null + doc.removeContent(0); // $ExpectType Content | null + + // https://developers.google.com/apps-script/reference/xml-service/element + const element = XmlService.createElement("element"); // $ExpectType Element + const namespace = XmlService.getNamespace("uri"); // $ExpectType Namespace + element.getAttribute("attr"); // $ExpectType Attribute | null + element.getAttribute("attr", namespace); // $ExpectType Attribute | null + element.getChild("child"); // $ExpectType Element | null + element.getChild("child", namespace); // $ExpectType Element | null + element.getChildText("child"); // $ExpectType string | null + element.getChildText("child", namespace); // $ExpectType string | null + element.getContent(1); // $ExpectType Content | null + element.getDocument(); // $ExpectType Document | null + element.getNamespace("prefix"); // $ExpectType Namespace | null + element.getParentElement(); // $ExpectType Element | null + element.removeContent(1); // $ExpectType Content | null + + // https://developers.google.com/apps-script/reference/xml-service/entity-ref + const entityRef = content.asEntityRef() as GoogleAppsScript.XML_Service.EntityRef; + entityRef.getParentElement(); // $ExpectType Element | null + entityRef.getPublicId(); // $ExpectType string | null + entityRef.getSystemId(); // $ExpectType string | null + + // https://developers.google.com/apps-script/reference/xml-service/format + XmlService.getCompactFormat().setIndent(null).format(element); + + // https://developers.google.com/apps-script/reference/xml-service/processing-instruction + const processingInstruction = content + .asProcessingInstruction() as GoogleAppsScript.XML_Service.ProcessingInstruction; + processingInstruction.getParentElement(); // $ExpectType Element | null + + // https://developers.google.com/apps-script/reference/xml-service/text + const text = XmlService.createText(""); + text.getParentElement(); // $ExpectType Element | null +}; + const createFolderAndGetDescription = () => { // Create folder. const folder = DriveApp.createFolder("MyFolder"); @@ -333,7 +451,7 @@ const createFolderAndGetDescription = () => { // Set description. folder.setDescription("desc"); // Get description. Expect 'DESC'. - Logger.log(folder.getDescription().toUpperCase()); + Logger.log(folder.getDescription()?.toUpperCase()); }; function onChange(e: GoogleAppsScript.Events.SheetsOnChange) { @@ -355,7 +473,7 @@ const createFileAndGetDescription = () => { // Set description. file.setDescription("desc"); // Get description. Expect 'DESC'. - Logger.log(file.getDescription().toUpperCase()); + Logger.log(file.getDescription()?.toUpperCase()); }; function timeDriven(e: GoogleAppsScript.Events.TimeDriven) { @@ -412,6 +530,7 @@ DriveApp.createFile("", "").moveTo(DriveApp.getFolderById("")); // Addon event objects tests: const handleCalendarAction = (e: GoogleAppsScript.Addons.EventObject) => { + if (!e.calendar) return; const { calendar: { attendees, calendarId, recurringEventId }, } = e; @@ -487,6 +606,7 @@ const handleCalendarAction = (e: GoogleAppsScript.Addons.EventObject) => { }; const handleDocsAction = (e: GoogleAppsScript.Addons.EventObject) => { + if (!e.docs) return; const { docs: { addonHasFileScopePermission, id, title }, } = e; @@ -497,6 +617,7 @@ const handleDocsAction = (e: GoogleAppsScript.Addons.EventObject) => { }; const handleDriveAction = (e: GoogleAppsScript.Addons.EventObject) => { + if (!e.drive) return; const { drive: { activeCursorItem, selectedItems }, } = e; @@ -517,6 +638,7 @@ const handleDriveAction = (e: GoogleAppsScript.Addons.EventObject) => { }; const handleGmailAction = (e: GoogleAppsScript.Addons.EventObject) => { + if (!e.gmail) return; const { gmail: { messageId, threadId, bccRecipients = [], ccRecipients = [], toRecipients = [] }, } = e; @@ -532,9 +654,11 @@ const handleGmailAction = (e: GoogleAppsScript.Addons.EventObject) => { }; const handleSheetsAction = (e: GoogleAppsScript.Addons.EventObject) => { + if (!e.sheets) return; const { sheets: { addonHasFileScopePermission, id, title }, } = e; + if (!id) return; // $ExpectType Spreadsheet const spreadsheet = SpreadsheetApp.openById(id); @@ -550,9 +674,11 @@ const handleSheetsAction = (e: GoogleAppsScript.Addons.EventObject) => { }; const handleSlidesAction = (e: GoogleAppsScript.Addons.EventObject) => { + if (!e.slides) return; const { slides: { addonHasFileScopePermission, id, title }, } = e; + if (!id) return; const presentation = SlidesApp.openById(id); @@ -570,6 +696,7 @@ const handleCommonAction = (e: GoogleAppsScript.Addons.EventObject) => { const { commonEventObject: { formInputs, hostApp, parameters, platform, timeZone, userLocale }, } = e; + if (!timeZone) return; const plaformMap: { [P in GoogleAppsScript.Addons.Platform]: string } = { ANDROID: "Android", @@ -611,20 +738,24 @@ const handleCommonAction = (e: GoogleAppsScript.Addons.EventObject) => { }, } = formInputs[id]; - if (dateInput || dateInputRhino) { - parameters.modifiedAt = dateInput?.msSinceEpoch || dateInputRhino?.msSinceEpoch; + const dateSource = dateInput || dateInputRhino; + if (dateSource) { + parameters.modifiedAt = dateSource.msSinceEpoch; } - if (dateTimeInput || dateTimeInputRhino) { - parameters.modifiedAt = dateTimeInput?.msSinceEpoch || dateTimeInputRhino?.msSinceEpoch; + const dateTimeSource = dateTimeInput || dateTimeInputRhino; + if (dateTimeSource) { + parameters.modifiedAt = dateTimeSource.msSinceEpoch; } - if (stringInputs || stringInputsRhino) { - parameters.emails = JSON.stringify(stringInputs?.value || stringInputsRhino?.value); + const stringSource = stringInputs || stringInputsRhino; + if (stringSource) { + parameters.emails = JSON.stringify(stringSource.value); } - if (timeInput || timeInputRhino) { - const { hours, minutes } = timeInput || timeInputRhino; + const timeSource = timeInput || timeInputRhino; + if (timeSource) { + const { hours, minutes } = timeSource; parameters.startsAt = `${hours}:${minutes}`; } }); @@ -751,11 +882,13 @@ const handleScopeAction = () => { // Analytics Test const requestAnalyticsData = (): string => { + if (!Analytics.Data?.Ga) throw new Error(); const gaData = Analytics.Data.Ga.get("An Id", "2022-01-18", "2022-01-18", "Some metrics", { dimensions: "Some dimensions", }); const totalsForAllResults = gaData.totalsForAllResults; + if (!totalsForAllResults) throw new Error(); const totalSessions = totalsForAllResults["ga:sessions"]; return totalSessions; @@ -812,7 +945,7 @@ const mimeTypes: string[] = [MimeType.GOOGLE_APPS_SCRIPT]; // analytics reporting test const analyticsReporting = () => { - const gaData = AnalyticsReporting.Reports.batchGet({ + const gaData = AnalyticsReporting.Reports?.batchGet({ reportRequests: [ { viewId: "", @@ -913,7 +1046,7 @@ const blob = () => { const blob = Utilities.newBlob("content", "application/json"); blob.setContentType(null); - // $ExpectType string + // $ExpectType string | null const contentType = blob.getContentType(); return contentType; @@ -923,6 +1056,7 @@ const blob = () => { const sheetDataSource = () => { const sheet = SpreadsheetApp.getActiveSheet(); const dss = sheet.asDataSourceSheet(); + if (!dss) return; // methods dss.addFilter("column1", {} as unknown as GoogleAppsScript.Spreadsheet.FilterCriteria); @@ -948,17 +1082,18 @@ const sheetDataSource = () => { // Drive Activity (Advanced service) const driveActivity = () => { - const response = DriveActivity.Activity.query({ pageSize: 10, filter: "time > 1452409200000" }); - for (const activity of response.activities) { - const originalObject = activity.primaryActionDetail.create?.copy?.originalObject; - if (originalObject) { + const response = DriveActivity.Activity?.query({ pageSize: 10, filter: "time > 1452409200000" }); + for (const activity of response?.activities ?? []) { + const originalObject = activity.primaryActionDetail?.create?.copy?.originalObject; + if (originalObject && originalObject.driveItem) { console.log(originalObject.driveItem.file); // DriveFileReference.file is deprecated console.log(originalObject.driveItem.driveFile); console.log(originalObject.driveItem.folder); // DriveFileReference.folder is deprecated console.log(originalObject.driveItem.driveFolder); } - for (const target of activity.targets) { + for (const target of activity.targets ?? []) { const driveItem = target.driveItem; + if (!driveItem) continue; console.log(driveItem.file); // DriveFile.file is deprecated console.log(driveItem.driveFile); console.log(driveItem.folder); // DriveFile.folder is deprecated @@ -969,6 +1104,7 @@ const driveActivity = () => { // People_v1 (Advanced Service) const people = () => { + if (!People.People) return; // contacts batch methods const batchCreateContactsResponse = People.People.batchCreateContacts({ readMask: "names,emailAddresses", @@ -979,7 +1115,7 @@ const people = () => { }, }], }); - console.log(batchCreateContactsResponse.createdPeople[0].person.names); + console.log(batchCreateContactsResponse.createdPeople?.[0].person?.names); const batchUpdateContactsResponse = People.People.batchUpdateContacts({ updateMask: "names,emailAddresses", readMask: "names,emailAddresses", @@ -990,7 +1126,7 @@ const people = () => { }, }, }); - console.log(batchUpdateContactsResponse.updateResult.names); + console.log(batchUpdateContactsResponse.updateResult?.names); People.People.batchDeleteContacts({ resourceNames: ["people/test1234"] }); const image = DriveApp.getFileById("some-photo-data-file-id").getBlob(); @@ -1001,11 +1137,11 @@ const people = () => { photoBytes: baseImage, sources: ["READ_SOURCE_TYPE_PROFILE", "READ_SOURCE_TYPE_CONTACT"], }, "people/test0123"); - console.log(updateContactPhotoResponse.person.names); + console.log(updateContactPhotoResponse.person?.names); const deleteContactPhotoResponse = People.People.deleteContactPhoto("people/test0123", { sources: ["READ_SOURCE_TYPE_PROFILE", "READ_SOURCE_TYPE_CONTACT"], }); - console.log(deleteContactPhotoResponse.person.names); + console.log(deleteContactPhotoResponse.person?.names); // directory methods const searchDirectoryPeopleResponse = People.People.searchDirectoryPeople({ @@ -1013,24 +1149,25 @@ const people = () => { readMask: "names,emailAddresses", sources: ["DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE"], }); - console.log(searchDirectoryPeopleResponse.people[0].names); + console.log(searchDirectoryPeopleResponse.people?.[0].names); const listDirectoryPeopleResponse = People.People.listDirectoryPeople({ readMask: "names,emailAddresses", sources: ["DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE"], }); - console.log(listDirectoryPeopleResponse.people[0].names); + console.log(listDirectoryPeopleResponse.people?.[0].names); + if (!People.OtherContacts) return; // other contacts methods const otherContactsListResponse = People.OtherContacts.list({ readMask: "names,emailAddresses", sources: ["READ_SOURCE_TYPE_CONTACT", "READ_SOURCE_TYPE_PROFILE"], }); - console.log(otherContactsListResponse.otherContacts[0].names); + console.log(otherContactsListResponse.otherContacts?.[0].names); const otherContactsSearchResponse = People.OtherContacts.search({ query: "Foo", readMask: "names,emailAddresses", }); - console.log(otherContactsSearchResponse.people[0].names); + console.log(otherContactsSearchResponse.people?.[0].names); const otherContactsCopyResponse = People.OtherContacts.copyOtherContactToMyContactsGroup({ copyMask: "names,emailAddresses,phoneNumbers", }, "people/test0123"); @@ -1113,6 +1250,7 @@ function driveFileOperations() { description: "This is a description for a test file.", mimeType: MimeType.GOOGLE_DOCS, // Example MIME type }); + if (!createdFile.id) return; console.log("Created File:", createdFile.name, createdFile.id, createdFile.mimeType); // Get a file (replace with a valid Drive ID) @@ -1165,6 +1303,7 @@ function driveFileOperations() { const copiedFile = Drive.Files.copy({ name: "test_copy" }, createdFile.id); console.log("Copied File:", copiedFile.name, copiedFile.id); + if (!copiedFile.id) return; // (Don't forget to remove the copied file if you want to clean up) Drive.Files.remove(copiedFile.id); } @@ -1212,6 +1351,7 @@ function listDrives() { // Example: Create a comment and a reply function commentAndReply() { const comment = Drive.Comments.create({ content: "Comment text" }, "FileID", { fields: "id" }); + if (!comment.id) return; const reply = Drive.Replies.create({ content: "Reply text" }, "FileID", comment.id, { fields: "id" }); console.log(reply.id); } diff --git a/types/google-apps-script/tsconfig.json b/types/google-apps-script/tsconfig.json index 55f4aa430bed76..0a462cdede15cb 100644 --- a/types/google-apps-script/tsconfig.json +++ b/types/google-apps-script/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "types": [], "noEmit": true,