どのように取得したり、プロパティやNAVのHTML要素タグのメソッドのアクセスを使用してエラーを入力します?
4845 ワード
Originally posted here!
のプロパティとメソッドを取得またはアクセスするには
エラーや警告は、コンパイラが
TLドクター
こうすることができます.
として、TypeScriptコンパイラは、下に赤いsquiggly行を見せていることがわかります
このエラーを避けるために
タイプアサーションを行うには
こうすることができます.
上のコードはcodesandbox .
それで😃!
お気軽に共有する場合は、この便利な発見😃.
のプロパティとメソッドを取得またはアクセスするには
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 .
それで😃!
お気軽に共有する場合は、この便利な発見😃.
Reference
この問題について(どのように取得したり、プロパティやNAVのHTML要素タグのメソッドのアクセスを使用してエラーを入力します?), 我々は、より多くの情報をここで見つけました https://dev.to/melvin2016/how-to-get-or-access-the-properties-and-methods-of-nav-html-element-tag-without-errors-in-typescript-4j9iテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol