简体   繁体   English

如何使用 map 到 typescript 中的 object 键的字符串?

[英]How to use a string to map to an object key in typescript?

I am trying to assure if some object structure exist in the window object and if not exist create it.我试图确保 window object 中是否存在某些 object 结构,如果不存在则创建它。

My end Goal is to have this: window.Debug.ObjectCategory我的最终目标是拥有这个: window.Debug.ObjectCategory

I have a function that returns me a reference of window that is assured to contain Debug in it我有一个 function,它返回给我window的参考,确保其中包含Debug

interface MyWindow extends Window {
  Debug?: {
     [key in DebugCategories]?: {}
  }
}

enum DebugCategories {
  Category1 = 'Category1',
  Category2 = 'Category2',
}


function getWindowDebug(): Required<MyWindow> {
  if (!window.Debug) {
    window.Debug= {}
  }

  return window as Required<MyWindow>
}

but now I want to create a generic function where I can get a secure window.Debug.Category1 or window.Debug.Category2 but I can not figure out how to write the function return: but now I want to create a generic function where I can get a secure window.Debug.Category1 or window.Debug.Category2 but I can not figure out how to write the function return:

function getWindowWithCategory(category: DebugCategories ): Required<MyWindow > & WHAT_HERE? {
  const myWindow = getWindowDebug();

  if (!myWindow.Debug[category]) {
    window.Debug[category] = {}
  }

  return myWindow as ???;

}

Here is my stab at it.这是我的尝试。 I refactored the code some to make sure Debug is defined with its categories at the start, let me know if you are looking for a different return type for the getWindowWithCategory fn.我重构了一些代码以确保在开始时使用其类别定义 Debug,如果您正在为getWindowWithCategory fn 寻找不同的返回类型,请告诉我。

enum DebugCategory {
  Category1 = 'Category1',
  Category2 = 'Category2',
}

type Debug = Record<DebugCategory, {}>;

interface DebugWindow extends Window {
  Debug: Debug;
}

function getDebugWindow(): DebugWindow {
  const debugWindow = window as unknown as DebugWindow;
  if (debugWindow.Debug) {
    return debugWindow;    
  }
  
  debugWindow.Debug = {
    [DebugCategory.Category1]: {},
    [DebugCategory.Category2]: {},
  };
  return debugWindow;
}

function getDebugWindowCategory<T extends DebugCategory>(category: T): Debug[T] {
  return getDebugWindow().Debug[category];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM