简体   繁体   English

在Typescript中创建(甚至更多的泛型)函数

[英]Creating (even more generics) functions in Typescript

I am creating a simple hash table in Typescript and I have two functions, one that return all keys and another one that return all values, and I got something like this: 我在Typescript中创建一个简单的哈希表,我有两个函数,一个函数返回所有键,另一个函数返回所有值,并且我得到了如下信息:

  public values() {
    let values = new Array<T>();
    this._keyMap.forEach((element) =>
      element.forEach((innerElement) => values.push(innerElement.value))
    );
    return values;
  }

  public keys() {
    let values = new Array<string>();
    this._keyMap.forEach((element) =>
      element.forEach((innerElement) => values.push(innerElement.key))
    );
    return values;
  }

What I am trying to do know is to condense this two functions into one as much of the code is repetition, I would only have to pass the type to the functions (for the array) what is easy however for one I need to push innerElement.value and for the other innerElement.key so hopefully I would have something like: 我想做的就是将这两个函数压缩为一个,因为重复的代码很多,我只需要将类型传递给函数(对于数组),这很容易,但是对于一个我需要按下innerElement.value和其他innerElement.key所以希望我会像这样:

  public values() {
    return getArrayInfo<T>(/*code to return value*/);
  }
  public keys() {
    return getArrayInfo<String>(/*code to return keys*/);
  }

 public getArrayInfo<I>(/*something*/) {
    let values = new Array<I>();
    this._keyMap.forEach((element) =>
      element.forEach((innerElement) => values.push(/*something*/))
    );
    return values;
  }

What you have is pretty close to something. 您所拥有的几乎是什么。 You could use property index signatures. 您可以使用属性索引签名。

public values() {
    return getArrayInfo<T>('value');
  }
  public keys() {
    return getArrayInfo<String>('key');
  }

 public getArrayInfo<I>(key: string) {
    let values = new Array<I>();
    this._keyMap.forEach((element) =>
      element.forEach((innerElement) => values.push(innerElement[key]))
    );
    return values;
  }

However with this you will lose a lot of type safety, and you would probably want to add some undefined/null checking in the mix. 但是,这样做会损失很多类型安全性,并且您可能想在混合中添加一些未定义/空检查。

Based on Tim B James response I was able to come up with a solution that fully uses typescript, I posted it here in case some is interested: 根据Tim B James的回答,我提出了一个完全使用打字稿的解决方案,如果有兴趣,我将其张贴在这里:

  enum typeOfSearch {
    key = 'key',
    value = 'value'
  }

  public getArrayInfo<I>(type: typeOfSearch) {
    let values = new Array<I>();
    this._keyMap.forEach((element) =>
      element.forEach((innerElement) =>
        values.push(innerElement[type.valueOf()])
      )
    );
    return values;
  }

  public values() {
    return this.getArrayInfo<T>(typeOfSearch.value);
  }

  public keys() {
    return this.getArrayInfo<String>(typeOfSearch.key);
  }

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

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