typescript 打字稿中动态键的接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39256682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:18:37  来源:igfitidea点击:

Interface for dynamic key in typescript

typescript

提问by Manuel Schiller

I have an Object like this that is created by underscore's _.groupBy()method.

我有一个这样的对象,它是由下划线的_.groupBy()方法创建的。

myObject = {
  "key" : [{Object},{Object2},{Object3}],
  "key2" : [{Object4},{Object5},{Object6}],
  ...
}

How would I define that as an Interface with TypeScript? i don't want to simply define it as myObject:Object = { ...but rather have an own type for it.

我如何将其定义为 TypeScript 的接口?我不想简单地将它定义为,myObject:Object = { ...而是想为它定义一个自己的类型。

回答by Bruno Grieder

Your object looks like a dictionary of Objectarrays

你的对象看起来像一个Object数组字典

interface Dic {
    [key: string]: Object[]
}

回答by Mikael Couzic

There's now a dedicated Recordtype in TypeScript:

RecordTypeScript现在有一个专用类型:

const myObject: Record<string, object[]> = { ... }

Also, consider typing the keys whenever possible:

此外,请考虑尽可能键入键:

type MyKey = 'key1' | 'key2' | ...

const myObject: Record<MyKey, object[]> = { ... }

回答by Asutosh

don't know about interface, for dynamic objects we can go something like this:

不知道接口,对于动态对象,我们可以这样做:

let memoTable: { [k: number]: number } = {};
memoTable[1]=5;
memoTable[2]=7;

回答by Kriti

Instead of using Object as a type use Record

而不是使用对象作为类型使用记录

interface myObjInterface {
  [key: string]: Record<string, any>[]
}

回答by zemil

I would suggest a solution with Map, maybe for someone it will be useful:

我会建议使用 Map 的解决方案,也许对某人有用:

type TKey = 'key1' | 'key2' | 'key3';
type TValue = object[];

type TMapper = Map<TKey, TValue>; // But also you can use Record instead of Map