TypeScript类属性查找方法类型推断

问题描述 投票:1回答:1

我正在努力获取类型推断以用于类属性查找。

我想要的是:

class Family <T extends { [name: string]: Animal }> {
  public members: T

  public lookup <K extends keyof T>(name: K): T[K] {
    return this.members[name]
  }
}

class Animal {}
class Cat extends Animal {}
class Dog extends Animal {}

const cat = new Cat
const dog = new Dog

const foo = new Family
foo.members = { kitty: cat, bob: dog }
const result1 = foo.lookup('missing') // I want this to fail for missing key. It doesn't.
const result2 = foo.lookup('kitty') // I want this has inferred type Cat. It doesn't.

我相信上面是可以实现的,因为我得到的功能版本如下:>

function lookup <O, K extends keyof O> (obj: O, key: K): O[K] {
  return obj[key]
}

const o = { a:1, b: 'text'}
const r = lookup(o, 'a') // correctly inferred type number
const r2 = lookup(o, 'b') // correctly inferred type string

任何帮助或指南,我们将不胜感激。提前致谢。

我正在努力获取类型推断以用于类属性查找。我想要的是:类Family {公共成员:T公共查询

typescript typescript-typings type-inference typescript-generics static-typing
1个回答
1
投票

[通常在声明变量时推断变量的类型,并且变量通常在更改后不会更改(因此,foo键入为Family<{ [name: string]: Animal; >,因为在初始化时没有其他可用信息)]

如果可以将member传递给构造函数,则根据将按预期工作的参数来推断T

class Family <T extends { [name: string]: Animal }> {
  constructor(public members: T) { }

  public lookup <K extends keyof T>(name: K): T[K] {
    return this.members[name]
  }
}

const result1 = foo.lookup('missing') // err
const result2 = foo.lookup('kitty') // cat
© www.soinside.com 2019 - 2024. All rights reserved.