6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Class構文にTypeScriptを導入

Last updated at Posted at 2019-09-30

Class構文にTypeScriptを導入したときの備忘録になります。

document.querySelector

Sample.ts
class Sample {
  eventElement: HTMLInputElement;

  constructor(eventElement: string) {
    this.eventElement =  <HTMLInputElement>document.querySelector(eventElement);
  }
}

export default Sample;

document.querySelectorでelementを指定するときHTMLInputElementを記述しないと

TS2322: Type 'Element | null' is not assignable to type 'object'.

とエラーが表示される。

document.querySelectorAllの場合

Sample.ts
class Sample {
  targetElements: NodeListOf<HTMLElement>;

  constructor(targetElements: string) {
    this.targetElements = document.querySelectorAll(targetElements);
  }
}

export default Sample;

document.querySelectorと同じ記述(HTMLInputElement)をすると

Conversion of type 'NodeListOf<Element>' to type 'HTMLInputElement' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

このようなエラーになります。

document.scrollingElementの場合

Sample.ts
const scrollTopPosition: number = document.scrollingElement ? document.scrollingElement.scrollTop : 0;

document.scrollingElementがnullを返すので三項演算子で分岐

resizeイベントの場合

window.resizeのイベントが終わったら処理を走らすソースにになります。

Sample.ts
Class Sample {
  observeResize: NodeJS.Timer | null;

  constructor() {
    this.observeResize = null;
  }

  resizeWindow() {
    window.addEventListener('resize', () => {
      if (this.observeResize) {
        clearTimeout(this.observeResize);
        this.observeResize = null;
      }
      this.observeResize = setTimeout(() => {
       // 処理を書く
      }, 200);
    }, false);
  }
};

export default Sample;

参考サイト

6
5
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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?