firebase和typescript—类型为';{}';不可分配给类型为';消息';

firebase和typescript—类型为';{}';不可分配给类型为';消息';,typescript,firebase,google-cloud-functions,Typescript,Firebase,Google Cloud Functions,这是我第一次使用typescript,所以我决定将它与Firebase一起使用。 但我面临着我无法理解的错误 我写了两个文件MessageTemplate.ts和test.ts 运行后,一切正常 但是,当我试图将(firebase deploy——仅限函数)推送到firebase函数时,出现以下错误: > tsc src/index.ts:18:25 - error TS2345: Argument of type '{}' is not assignable to parameter

这是我第一次使用typescript,所以我决定将它与Firebase一起使用。 但我面临着我无法理解的错误

我写了两个文件
MessageTemplate.ts
test.ts
运行后,一切正常

但是,当我试图将(firebase deploy——仅限函数)推送到firebase函数时,出现以下错误:

> tsc

src/index.ts:18:25 - error TS2345: Argument of type '{}' is not assignable to parameter of type 'Message'.
  Property 'condition' is missing in type '{}' but required in type 'ConditionMessage'.

18  admin.messaging().send(payload)
                           ~~~~~~~

  node_modules/firebase-admin/lib/index.d.ts:410:3
    410   condition: string;
          ~~~~~~~~~
    'condition' is declared here.

src/index.ts:19:11 - error TS7006: Parameter 'fcm_response' implicitly has an 'any' type.

19    .then((fcm_response) => {
             ~~~~~~~~~~~~

src/index.ts:24:12 - error TS7006: Parameter 'error' implicitly has an 'any' type.

24    .catch((error) => {
              ~~~~~

src/MessageTemplate.ts:37:5 - error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature.

37     payload["notification"] = notification.toJSON()
       ~~~~~~~~~~~~~~~~~~~~~~~

src/MessageTemplate.ts:37:31 - error TS2532: Object is possibly 'undefined'.

37     payload["notification"] = notification.toJSON()
                                 ~~~~~~~~~~~~

src/MessageTemplate.ts:41:5 - error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature.

41     payload["data"] = data
       ~~~~~~~~~~~~~~~

src/MessageTemplate.ts:44:3 - error TS7017: Element implicitly has an 'any' type because type '{}' has no index signature.

44   payload[type] = to
     ~~~~~~~~~~~~~


Found 7 errors.

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! functions@ build: `tsc`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the functions@ build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /somepath/_logs/2019-03-26T21_04_51_135Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code2
函数/src/index.ts

import { buildPushNotification, SenderType } from "./MessageTemplate";
import * as functions from 'firebase-functions';
import * as admin from'firebase-admin';
admin.initializeApp();



export const sendMessage = functions.https.onRequest((request, response) => {
    // The topic name can be optionally prefixed with "/topics/".
    let topic = 'global'
    let data = {
        id:1024,
        name:"Juan"
    }
    let payload = buildPushNotification(SenderType.topic, topic, undefined, data)

    // Send a message to devices subscribed to the provided topic.
    admin.messaging().send(payload)
      .then((fcm_response) => {
        // Response is a message ID string.
        console.log('Successfully sent message:', fcm_response);
        response.send("Successfully sent message");
      })
      .catch((error) => {
        console.log('Error sending message:', error);
        response.send("Error");
      });
});
MessageTemplate.ts

export enum SenderType {
  token="token", 
  topic="topic", 
  condition="condition"
}

export class PNotification {

    title:string
    body:string

    constructor(title:string, body:string) { 
      this.title = title 
      this.body = body
  }

  toJSON():any {
    return {
      "title":this.title,
      "body":this.body
    }
  } 
}

function isNullOrUndefined(data:any){
  return data === null || typeof data === 'undefined' 
}

export function buildPushNotification(type:SenderType, to:string, notification?:PNotification, data?:any){

  let payload = {}

  if(!isNullOrUndefined(notification)) {
    payload["notification"] = notification.toJSON()
  }

  if(!isNullOrUndefined(data)) {
    payload["data"] = data
  }

  payload[type] = to

  return payload
}
test.ts

import { PNotification, buildPushNotification, SenderType } from "./MessageTemplate";



let notification = new PNotification("title 1", "body 1")
let data = {
    id:1024,
    name:"Juan"
}

let to = "AISA143f43533d32d3243d546fwf234"
let topic = "global"

let payload1 = buildPushNotification(SenderType.token, to, notification)
console.log(payload1)
函数/tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2015"
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

当您在本地运行时,由于您没有使用
tsconfig.json
,编译器使用的设置没有您尝试推送时严格,在推送时存在
tsconfig.json
,并且启用了一些可用的严格选项,即
strict
noImplicitReturns
noUnusedLocals

这是和的文档

为了显示您在本地成功编译的文件中的
strict
错误,我将它们添加到了一个单独的文件中。如果单击
选项
按钮并启用严格选项,您将看到错误

这是

为了修复
负载[…]
左侧错误,我添加了一个界面:

interface Payload {
    notification?: any
    data?: any
    token?: string
    topic?: string
    condition?: string
}
这定义了每个可能属性的类型,这些属性都是可选的,因为它们包括

有效负载
声明现在变为:

let payload: Payload = {}
由于
payload
及其属性现已键入,因此
noImplicitAny
错误已修复

为了修复
notification.toJSON
右侧错误,我添加了一个类型保护,以确保
notification
是正确的类型:

if (!isNullOrUndefined(notification)) {
    if (notification instanceof PNotification) {
        payload.notification = notification.toJSON()
    }
}
您可能希望更改
isNullOrUndefined
函数,而不是使用此函数。如果是这样,您可以使用用户定义的类型保护(请参阅和)


要修复其他错误,我建议使用vscode或类似的工具,使用与Firebase相同的
tsconfig.json
,以便您可以在本地看到错误,并在编辑器中显示可能的修复。或者,如果您愿意并且能够,您可以从Firebase中删除严格的设置
tsconfig.json

您在运行和尝试推送时是否使用相同的
tsconfig.json
?我甚至不知道存在tsconfig.json。我刚刚读过这篇文章,并用firebase函数/tsconfig.json进行了更新。回答您的问题:我没有使用相同的tsconfig.json,实际上,在运行tsc MessageTemplate.ts之后,我在同一个文件夹中没有任何tsconfig.json。