どのようにして取得するか、またはプロパティのメソッドとdivのHTML要素タグのメソッドのエラーなしで入力スクリプト?


Originally posted here!
のプロパティとメソッドを取得またはアクセスするにはdiv HTML Elementタグは、エラーが発生しないか、またはtypescriptで赤いsquiggly線を持たない場合、div HTML要素タグHTMLElement タイプスクリプトのインタフェース
エラーや警告は、コンパイラがdiv HTML要素タグ時間前に.しかし、私たちはdiv HTMLタグを使用しているので、HTMLElement プロパティとメソッドの宣言を含むインターフェイスです.

TLドクター
// get reference to the first 'div'
// HTML element tag in the document
// with type assertion using the HTMLElement interface
const divTag = document.querySelector("div") as HTMLElement;

// no errors or red squiggly lines will be
// shown while accessing properties or methods
// since we have asserted the type
// for the 'div' HTML element tag 😍
const id = divTag.id;
それをよりよく理解するために、我々が第1を選んでいると言いましょうdiv HTML要素タグdocument.querySelector() このような方法
// get reference to the first 'div'
// HTML element tag in the document
const divTag = document.querySelector("div");
では、プロパティの値を取得しようとしましょうid を使うdiv 属性としてHTML要素タグ.
こうすることができます.

として、TypeScriptコンパイラは、下に赤いsquiggly行を見せていることがわかりますdivTag オブジェクト.あなたが上で震えるならばdivTag と言うエラーが表示されますObject is possibly 'null' . これはtypescriptがdivTag オブジェクトは、プロパティやメソッドを事前に持ちます.
このエラーを避けるためにdiv HTML要素タグHTMLElement タイプスクリプトのインタフェース
タイプアサーションを行うにはas キーワード以降document.querySelector("div") メソッドの後にHTMLElement .
こうすることができます.
// get reference to the first 'div'
// HTML element tag in the document
// with type assertion using the HTMLElement interface
const divTag = document.querySelector("div") as HTMLElement;

// no errors or red squiggly lines will be
// shown while accessing properties or methods
// since we have asserted the type
// for the 'div' HTML element tag 😍
const id = divTag.id;
今以上のホバーid プロパティdivTag オブジェクトTypescriptは、再びクールで、開発中の生産性と明快さを増加させるプロパティ自体についてより多くの情報を示します.

上のコードはcodesandbox .
それで😃!

お気軽に共有する場合は、この便利な発見😃.