LoginSignup
0
1

More than 1 year has passed since last update.

FlatpickrのmethodをTypeScriptで使用する

Posted at

Flatpickrの公式ドキュメントのコードを貼り付けたが、TSで怒らるし意味不明という方へ

例えば公式のこんなコード
https://flatpickr.js.org/instance-methods-properties-elements/#methods

let calendar = flatpickr(yourElement, config);
calendar.changeMonth(1); // go a month ahead

これを貼り付けてもTypeScriptの設定によっては、
プロパティ 'changeMonth' は型 'Instance | Instance[]' に存在しません。
と怒られます。他のmethodsでも同様にキレられますよね。

こんなコードに変更すると解決できるかもしれません。

const myCalendar = document.querySelector('.yourElement');
if(myCalendar) {
  const fp = flatpickr(myCalendar, config);
  fp.changeMonth(1);
}

if文を使い、取得したElementがnullでないことを伝えてあげてからだとうまくmethodにアクセスできると思います。

私自身TypeScript使い始めですが、TSはとにかく存在を確約してあげないと「そんな要素無いかもしれないだろ!つまりここも無い可能性!」と怒ってきますね。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1