firebase и typcript - Аргумент типа '{}' не может быть назначен параметру типа 'Message' - PullRequest
1 голос
/ 27 марта 2019

Я впервые использую машинопись, поэтому я решил использовать ее с Firebase. Но я сталкиваюсь с ошибками, которые не могу понять.

Я написал два файла MessageTemplate.ts и test.ts После запуска их все отлично работает.

Но когда я пытаюсь передать (firebase deploy --only functions) их в firebase-functions, у меня появляются следующие ошибки:

> 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"
  ]
}

1 Ответ

0 голосов
/ 29 марта 2019

Когда вы работаете локально, так как вы не используете tsconfig.json, компилятор использует менее строгие настройки, чем при попытке нажать, где есть tsconfig.json с некоторыми из доступных строгих опций, например strict, noImplicitReturns и noUnusedLocals.

Вот документация для tsconfig.json и опций компилятора

Для отображенияstrict ошибок в файлах, которые вы успешно скомпилировали локально, я добавил их в один файл на TypeScript Playground .Если вы нажмете кнопку Options и включите строгие параметры, вы увидите ошибки.

Вот другая игровая площадка с удаленными ошибками .

Чтобы исправить payload[...] ошибки левой стороны, я добавил интерфейс:

interface Payload {
    notification?: any
    data?: any
    token?: string
    topic?: string
    condition?: string
}

Это определяет типы для каждого из возможных свойств, которые являются необязательными, поскольку они включают ?.

Объявление payload теперь становится:

let payload: Payload = {}

Поскольку payload и его свойства теперь набраны, ошибки noImplicitAny были исправлены.

Исправление notification.toJSON ошибка правой стороны, я добавил защиту типа, чтобы гарантировать, что notification является правильным типом:

if (!isNullOrUndefined(notification)) {
    if (notification instanceof PNotification) {
        payload.notification = notification.toJSON()
    }
}

Вы можете изменить функцию isNullOrUndefined вместо использования.Если это так, вы можете использовать определяемый пользователем тип защиты (см. здесь и здесь ).

Чтобы исправить другие ошибки, я бы порекомендовал использовать vscode или аналогичныйс тем же tsconfig.json, что и в Firebase, так что вы можете увидеть ошибки локально и показать возможные исправления в редакторе.Кроме того, если вы предпочитаете и можете, вы можете удалить строгие настройки из Firebase tsconfig.json.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...