창 사용 중지
4154 단어 windowtypescriptglobal
TLDR;
시간 제한이 있는 사람을 위해
// instead of this
(window as any).MY_GREETING_MESSAGE = 'Hi Earth!'
// do this
declare global {
interface Window {
MY_GREETING_MESSAGE: string
}
}
window.MY_GREETING_MESSAGE = 'Hi Earth!'
Typescripter 여러분은
window
와 같은 전역 범위 변수에 무언가를 입력해야 하는 상황을 발견했을 수 있습니다.javascript
의 경우 다음과 같은 복잡한 단계 없이 쉽게 무언가를 넣을 수 있습니다.// running in browser
window.MY_GREETING_MESSAGE = 'Hi Earth!'
그러나 작업 중인 객체 속성이 실제로 정적 유형 언어의 보기에 존재하는지 여부를 확인하는 일부 유형 검사를 수행하는 Typescript로. 이 작업을 직접 수행하는 것은 금지됩니다.
window.MY_GREETING_MESSAGE = 'Hi Earth!'
// ^^
// Property 'MY_GREETING_MESSAGE' does not exist on type 'Window & typeof globalThis'.ts(2339)
왜요?
이 전역
Window
변수에 대해 선언하는 인터페이스window
에는 MY_GREETING_MESSAGE
속성이 없기 때문에 대답은 매우 간단합니다.
여느 때처럼 창문이 온다
대부분의 새로운 Typescript 개발자는 이 문제를 해결할 수 없으며 명시적으로
window
를 any
로 캐스트하는 것과 같은 더러운 해결 방법을 적용할 수 있습니다.(window as any).MY_GREETING_MESSAGE = 'Hi Earth!'
유형을 다시 가져옵니다.
As
window
는 Typescript 라이브러리의 표준 Ambient 유형에 의해 선언되었습니다. 더 나은 접근 방식은 이 유형을 다음과 같이 확장하는 것입니다.declare global {
interface Window {
MY_GREETING_MESSAGE: string
}
}
window.MY_GREETING_MESSAGE = 'Hi Earth!'
이렇게 하면 Typescript가 주변
window
객체에 넣고자 하는 속성을 인식하게 됩니다.
noted that you need to make sure the value has been assigned before use, or you may make it as an optional property
행복한 코딩!
Reference
이 문제에 관하여(창 사용 중지), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/zapkub/stop-using-window-as-any-41i1텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)