简体   繁体   English

在(打字稿)中处理接口中的复杂类型

[英]working with complex types in interfaces in (typescript)

I'm pretty new to type script and java script.我对键入脚本和 java 脚本很陌生。

My question is: I have an interface, in which one of it's properties is Map .我的问题是:我有一个接口,其中一个属性是 Map 。

I have a json object that is the same structure as the interface, when one of it's entries is another object.我有一个与接口结构相同的 json 对象,当它的一个条目是另一个对象时。 I'm trying to assign the json object to variable of the interface, but when i try to use the Map functions it says that it these functions do not exist.我试图将 json 对象分配给接口的变量,但是当我尝试使用 Map 函数时,它说这些函数不存在。

it's probably because Map is not initialized.这可能是因为 Map 未初始化。

for example, this is the json object:例如,这是 json 对象:

let obj = 
{
  firstArg: "first"
  secondArg: {one: 1, two: 2}
}

and this is the interface:这是界面:

interface example {
  firstArg: string,
  secondArg: Map<string , number>
}

Doing:正在做:

let exm: example = obj;
exm.secondArg.values().next()

is not working.不管用。

what is the best solution to make this work?使这项工作的最佳解决方案是什么?

An Object is not a Map . Object不是Map You will need to convert between Object s and Map s yourself:您需要自己在ObjectMap之间进行转换:

function objectToMap<K extends string, V>(obj: Record<K,V>): Map<K, V> {
  // return new Map(Object.entries(obj)); 
  const map = new Map<K, V>();
  Object.keys(obj).forEach((k:K) => map.set(k, obj[k]));
  return map;
}

function mapToObject<K extends string, V>(map: Map<K, V>): Record<K, V> {
  const obj = {} as Record<K, V>;
  map.forEach((v, k) => { obj[k] = v; });
  return obj;
}

So you could do:所以你可以这样做:

let obj =
  {
    firstArg: "first",
    secondArg: objectToMap({ one: 1, two: 2 })
  }


let exm: example = obj; // works now
exm.secondArg.values().next()

Using something like objectToMap() and mapToObject() , you will need to write code that converts between the JSON you are getting/sending and your data model with Map s in it.使用诸如mapToObject() objectToMap()mapToObject() ,您将需要编写代码来在您正在获取/发送的 JSON 和其中包含Map的数据模型之间进行转换。 Hope that helps;希望有所帮助; good luck!祝你好运!

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

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