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