ค้นหาเว็บไซต์

momentjs - ล้มเหลวในการสร้าง moment.js typescript เนื่องจากความขัดแย้งของชนิด MomentInput


ฉันมีโค้ด TypeScript ดังต่อไปนี้

import * as moment from "moment"

const months = this.getMonths();
const firstMonth = moment.min(months).startOf("month");
const lastMonth = moment.max(months).startOf("month");

public getMonths(): Array<moment.Moment> {
    const assignmentMonths = _.map(this.internalBudget.categoryAssignments, a => a.month);
    const transactionMonths = _.map(this.internalBudget.transactions, a => a.date);

    return _.concat(assignmentMonths, transactionMonths);
}

นั่นกำลังแสดงข้อผิดพลาดดังต่อไปนี้สำหรับบรรทัด moment.min และ moment.max เมื่อรัน tsc

TS2345: Argument of type 'Moment[]' is not assignable to parameter of type 'MomentInput'.
  Type 'Moment[]' has no properties in common with type 'MomentInputObject'.

ไฟล์ tsconfig.json ของฉันคือ

{
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "es6",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipDefaultLibCheck": true,
    "lib": [ "es6", "dom" ],
    "types": [ "node", "jasmine" ]
  },
  "exclude": [ "bin", "node_modules" ],
  "atom": { "rewriteTsconfig": false }
}

ฉันไม่สามารถหาข้อมูลใด ๆ ในเอกสารที่กล่าวถึงวัตถุ MomentInput หรือหาวิธีที่จะทำให้มันคอมไพล์ได้อย่างถูกต้อง จากเอกสารของ moment.js ดูเหมือนว่าฉันควรจะสามารถส่งอาร์เรย์ของ Moments ไปยัง min/max ได้ แต่ฉันเข้าใจว่านี่เป็นเพียง javascript และไม่ได้มีแนวคิดเรื่อง typescript ในระดับนั้น

ฉันพยายามสร้างวัตถุ MomentInput แต่ดูเหมือนว่าจุดประสงค์ของมันจะมีไว้สำหรับโมเมนต์เดียวมากกว่ามากกว่าลำดับอาร์เรย์ ฉันจะทำให้มันสร้างได้อย่างไร เวอร์ชันของทุกอย่างคือ:

  • ไทป์สคริปต์: 2.4.1
  • โหนด: 6.11.0
  • เอ็นพีเอ็ม: 3.10.10

คำตอบ #1

ฉันทำให้มันทำงานโดยใช้ตัวกระจาย (spread operator) แบบนี้: แทนที่จะใช้ moment.min(dates) ฉันใช้ moment.min(...dates)

คำตอบ #2

การลดเวอร์ชันลงไปที่ Typescript 2.3.4 ทำให้ทุกอย่างทำงานได้ดีมาก ผมไม่รู้ว่าเวอร์ชัน 2.4.1 เพิ่งถูกปล่อยออกมาไม่กี่ชั่วโมงก่อนคำถามของผม ดังนั้นน่าจะยังมีปัญหาเล็กน้อยกับการกำหนดประเภทของ moment.js ตอนนี้