Typescript: Access window object with type check

2022-09-21 10:28:04 浏览数 (1)

  • Backgrounds

Backgrounds

代码语言:javascript复制
"typescript": "3.7.2"

Our Requirements

We have an external html provide window.configs.

We may need to access window object in typescript to get config properties, and do validation before initial async request.

windowConfig.tsx :

代码语言:javascript复制
interface iConfig extends Window {
  config: {
    username: string,
    server: string,
    port: number,
  }
}

declare var window: iConfig;

export const windowConfig = window;

index.tsx :

代码语言:javascript复制
import { windowConfig } from './windowConfig';

/* use windowConfig as 'window' */

Alternative Solution

代码语言:javascript复制
import { useEffect } from 'react';

/* Add declaration for window.AMap */
declare let AMap;

export default function Map() {
  let map;

  useEffect(() => {
    /* Directly use AMap */
    map = new AMap.Map(`container`, {
      zoom: 10,
    });
  }, []);

  return (
    /* ... */
  );
}

0 人点赞