[Typescript] Using Variables Declared Elsewhere

The declare keyword in TypeScript allows you to specify types for global variables. Whenever you use it, an ambient context is created, which means that the variable is injected without needing to provide an implementation.

Here's how we would use declare to specify the type for DEBUG, which we'll type as an empty object for now:

declare const DEBUG: {};

This tells TypeScript that DEBUG is a constant that doesn't need to provide an implementation.

declare const DEBUG: {
  getState: () => {
    id: string;
  };
};

const state = DEBUG.getState(); // red squiggly line under getState

type test = Expect<Equal<typeof state, { id: string }>>;

 

How to use this declarion in anothe file?

1. Create a .d.tsfile

declare const DEBUG: {
  getState: () => {
    id: string;
  };
};

Then DEBUGis globally available

 

2. use declare global

If we don't create a .d.ts file, we can use

declare global {
  const DEBUG: {
      getState: () => {
        id: string;
      };
  };
};

 

posted @ 2024-08-07 19:13  Zhentiw  阅读(2)  评论(0编辑  收藏  举报