Why are SDK resources considered optional in @types/google-apps-script?

Viewed 76
2 Answers

Bottom line: "because they said so".

In the DefinitelyTyped definitions file linked in your question, those properties have been optional since the file was created. As per your question, the directory API in the official Google Node.JS SDK does indeed declare these properties as required. Therefore, it's impossible to tell whether this was an intentional decision by the person(s) responsible for the DefinitelyTyped definitions, and if so, what prompted it.

Your best options here are to either type cast the value as Required<AdminDirectory> if you're certain that those properties will always exist (not ideal), or to create an issue on the DefinitelyTyped repository, getting clarification and/or fixing the typings for potential future users.

This particular setup stems from the advanced service generator of type declaration files. In particular, you need to look at the parser module's Field class that prints interface fields. Its toString method is the one responsible for the fields being generated as optional (+ "?: " +):

toString = (depth: number): string => {
  const indent = " ".repeat(tabWidth * depth);
  let output = "";
  if (this.comment) {
    output += this.comment.toString(depth);
  }
  output += indent + this.name + "?: " + this.typeName + ";\n";
  return output;
};

Any field generated with it will have an optional modifier.

A simplified TypeScript playground demonstrates the behavior.

I have opened an issue on the generator repository to get some clarifications and discuss possibilities for addressing that.

Related