The built in web based editing environment for Apps Script does not interpret function return types, but you can give it a hint.
Introduction
Editing code behind in your Google docs and spreadsheets, etc. does not interpret a variable type when it has its value set from a function call. This means you lose the benefits of the built in method name auto complete and so it's far too easy to introduce bugs. However, this is easily fixed.
The Problem
Consider the following source:
var myLib = (function () {
var _ss
var DATA_SOURCE_ID = '1234567890123456789012345678901234567890ABCD'
function getSS() {
if (!_ss) {
_ss = SpreadsheetApp.openById(DATA_SOURCE_ID)
}
return _ss
}
function countTabs () {
var ss = getSS()
return ss.getSheets().length
}
})()
When you are writing the method countTabs
and type the ".", you would expect to get a popup IntelliSense panel. However, nothing appears!
The problem is that the Apps Script editor is not able to infer that the call to getSS()
always returns a Spreadsheet
object.
The Fix
You can fix this problem using a comment.
Change the getSS
method function to look like a simple variable assignment in a comment like this:
function getSS() {
if (!_ss) {
_ss = SpreadsheetApp.openById(DATA_SOURCE_ID)
}
return _ss
}
Then when you start wrinting code that has been assigned a value from the function, it will have the correct intellisense, almost as though you were using a typed language.
Hopefully, this will aid your productivity in Apps Script, especially if you are trying to write clean, DRY code, etc.
History
- 6th May, 2020: Initial version
I have been a software developer for about 20 years, mostly in small IT department that means you do all the roles all the time from 1st line support to 3rd line diagnostics and help authoring. To be fair, I don't do enough of the later which in turn causes way too much of the former with new staff always ready to show you how unintuitive your interfaces are!
I generally consider myself a "data plumber" with the majority of my work in back end SQL. If I could rule the world by writing a SPROC I would....
New definition of Stoicism: Someone who start a career in I.T. and still has a career in I.T. after 20 years!