0

我正在寻找一个像这样的通用类:

export abstract class Foo<ID extends keyof T, T> {
    bar(T t) {
        const s: string = t[ID];
    }
}

显然,上面的代码无法推断出的类型,t[ID]我们得到了一个隐含的any. 我怎样才能强制使用泛型T[ID]将是一个string

4

1 回答 1

1

Your code doesn't compile so I changed it to something that will:

export abstract class Foo<ID extends string, T extends Record<ID, string>> {

  // add a property of type ID.
  constructor(public id: ID) { } 

  // change the Java-esque (T t) to (t: T)
  bar(t: T) {
    //use the id property to index t; can't use type ID at runtime
    const s: string = t[this.id]; 
  }

}

The way to enforce the relationship you want is: instead of constraining ID to keyof T, you constrain T to Record<ID, string> where Record<K, V> is a type from the standard TypeScript library describing any object with keys from K and values from V. Hope that helps. Good luck.

于 2018-04-13T15:19:22.717 回答