どのように取得したり、プロパティやNAVのHTML要素タグのメソッドのアクセスを使用してエラーを入力します?


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

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

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

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

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

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

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