如何解决“错误TS2345:类型为实参”不能分配给类型为“ Params $ Resources $ Scripts $ Run”的参数

时间:2019-08-03 19:45:52

标签: angular typescript google-apps-script-api

我正在尝试利用Google Apps脚本API来运行预制的Google Apps脚本。不幸的是,并非所有示例文档都适用于Angular,但是node.js与此相似,我一直在尝试用angular重做它。我一直收到此错误,并且不明白这里出了什么问题,因为我似乎在给API函数脚本。运行它应该询问的参数。

我得到的全部错误是

  

node_modules / google-auth-library / build / src / auth / oauth2client.d.ts(298,55)中的错误:错误TS1039:在环境中不允许初始化程序。   src / app / app.component.ts(98,3):错误TS2345:类型为'{auth:> any;资源:{函数:字符串; }; scriptId:字符串; }”>不能分配给“ Params $ Resource $ Scripts $ Run”类型的参数。    对象文字只能指定已知的属性,而'resource'在'Params $ Resource $ Scripts $ Run'类型中不存在。

我尝试更改资源的类型:{function:string}以查看是否有帮助,但无济于事。这里的文档:https://developers.google.com/apps-script/api/reference/rest/v1/scripts/run

似乎暗示这些是它想要的参数。

这是app.component.ts中的代码

import { Component } from '@angular/core';
var file = require('file-system');
var fs = require('fs');
//import { readFile } from 'fs';
const readline = require('readline');
//const {google} = require('googleapis');
import { google } from "googleapis";



@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  // If modifying these scopes, delete token.json.
  SCOPES = ['https://www.googleapis.com/auth/script.projects'];
  // The file token.json stores the user's access and refresh tokens, and is
  // created automatically when the authorization flow completes for the first
  // time.
  TOKEN_PATH = 'token.json';  

constructor() {


// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Apps Script API.
  this.authorize(JSON.parse(content), this.callAppsScript);
});
}

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
 authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(this.TOKEN_PATH, (err, token) => {
    if (err) return this.getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
 getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: this.SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(this.TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', this.TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Creates a new script project, upload a file, and log the script's URL.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
 callAppsScript(auth) {
 // eslint-disable-line no-unused-vars
    const scriptId = 'MQjfx_a74LdckdFiqPexPXbj574JS7smg';
    const script = google.script('v1');


// Make the API request. The request object is included here as 'resource'.
script.scripts.run({
  auth: auth,
  resource: {
    function: 'myFunction',
  },
  scriptId: scriptId,
}, function(err, resp) {
  if (err) {
    // The API encountered a problem before the script started executing.
    console.log('The API returned an error: ' + err);
    return;
  }
  if (resp.error) {
    // The API executed, but the script returned an error.

    // Extract the first (and only) set of error details. The values of this
    // object are the script's 'errorMessage' and 'errorType', and an array
    // of stack trace elements.
    const error = resp.error.details[0];
    console.log('Script error message: ' + error.errorMessage);
    console.log('Script error stacktrace:');

    if (error.scriptStackTraceElements) {
      // There may not be a stacktrace if the script didn't start executing.
      for (let i = 0; i < error.scriptStackTraceElements.length; i++) {
        const trace = error.scriptStackTraceElements[i];
        console.log('\t%s: %s', trace.function, trace.lineNumber);
      }
    }
  } else {
    // The structure of the result will depend upon what the Apps Script
    // function returns. Here, the function returns an Apps Script Object
    // with String keys and values, and so the result is treated as a
    // Node.js object (folderSet).
    const folderSet = resp.response.result;
    if (Object.keys(folderSet).length == 0) {
      console.log('No folders returned!');
    } else {
      console.log('Folders under your root folder:');
      Object.keys(folderSet).forEach(function(id) {
        console.log('\t%s (%s)', folderSet[id], id);
      });
    }
  }
});
}
}

预期结果应为正在调用并运行的函数。相反,我得到了错误:

ERROR in node_modules/google-auth-library/build/src/auth/oauth2client.d.ts(298,55): error TS1039: Initializers are not allowed in ambient contexts.
src/app/app.component.ts(98,3): error TS2345: Argument of type '{ auth: any; resource: { function: string; }; scriptId: string; }' is not assignable to parameter of type 'Params$Resource$Scripts$Run'.
  Object literal may only specify known properties, and 'resource' does not exist in type 'Params$Resource$Scripts$Run'.

0 个答案:

没有答案