简体   繁体   English

从泛型类型推断返回类型?

[英]Inferring return type from generic type?

The following works but .getData() has a return type of any which isn't ideal as this is a consumer face API call.以下有效,但.getData()的返回类型为any ,这并不理想,因为这是消费者面部 API 调用。

In reality the return type here isn't any thing, but is strictly dependant on the type of object held in the items array.实际上,这里的返回类型不是any东西,而是严格依赖于 items 数组中保存的对象类型。

Is there anyway I can provide a return type to consumer of this method?无论如何,我可以向此方法的使用者提供返回类型吗?

class Group<T> {
  items: Array<T> = [];

  addItem(item: T) {
      this.items.push(item);
  }

  getData(itemIndex: number) {
    // Any is T
    return (this.items[itemIndex] as any).data;
  }
}

class NumberItem {
  data: number;

  constructor(data: number) {
      this.data = data;
  }
}

class StringItem {
  data: String = "";

  constructor(data: String) {
      this.data = data;
  }
}

let n1 = new NumberItem(3);
let n2 = new NumberItem(4);

let g1 = new Group<NumberItem>();
g1.addItem(n1);
g1.addItem(n2);

console.log(g1.getData(1));

Playground Link 游乐场链接

Give T an upper bound so that it has a data property, then the return type is T['data'] .T一个上限,使其具有data属性,则返回类型为T['data'] This way there is also no need for a type assertion inside the getData method.这样,在getData方法中也不需要类型断言。

class Group<T extends { data: any }> {
  items: Array<T> = [];

  addItem(item: T) {
    this.items.push(item);
  }

  getData(itemIndex: number): T['data'] {
    return this.items[itemIndex].data;
  }
}

Usage:用法:

let n1 = new NumberItem(3);
let n2 = new NumberItem(4);

let g1 = new Group<NumberItem>();
g1.addItem(n1);
g1.addItem(n2);

// result: number
const result = g1.getData(1);

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

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