如何向 TypeScript 指示对象的 属性 扩展了对象?

How to indicate to TypeScript that a property of an object extends object?

我实际上是在尝试创建一个 class,它使对象的所有属性都可以通过对象上的 get 函数访问。这些获取操作应该是可链接的。我想要的行为的一个例子:

最终目标

const original = {
  property: {
    interiorProperty: 'value';
  }
};
const wrapped = new Wrapper(original);

console.log(wrapped.get('property'));
// {
//   interiorProperty: 'value';
// }

console.log(wrapped.get('property').get('interiorProperty'));
// 'value'

我这样做的原因是为了在 Angular 模板中更好地 属性 访问。

但是,对象的某些属性(或属性的属性)最终将是基元。我以为我在考虑这个 - 然而,TypeScript 不同意。

当前代码

class Wrapper<OriginalType extends object> {
  private originalObject: OriginalType;

  constructor(obj: OriginalType) {
    this.originalObject = obj;
  }

  public get<Key extends keyof OriginalType>(key: Key) {
    const value = this.originalObject[key];
    if (typeof value === 'object') {
      // Error: Argument of type 'OriginalType[Key]' is not assignable to parameter of type 'object'.
      return new Wrapper(value);
    }
    return value;
  }
}

完整的 TypeScript 错误:

Argument of type 'OriginalType[Key]' is not assignable to parameter of type 'object'.
  Type 'OriginalType[keyof OriginalType]' is not assignable to type 'object'.
    Type 'OriginalType[string] | OriginalType[number] | OriginalType[symbol]' is not assignable to type 'object'.
      Type 'OriginalType[string]' is not assignable to type 'object'.ts(2345)

我不明白为什么 typeof 检查没有告诉 TypeScript value 在 if 块内扩展对象。我认为这可能与类型 Key 没有被缩小有关,但是当我喜欢在那里输入时 (key: OriginalType[Key] extends object ? Key : never) 它仍然没有效果。

我确定有办法实现这一点,问题只是我的专业知识,但我终究无法弄清楚。

您在 extend 上打错了,object 应该是 Object

class Wrapper<OriginalType extends Object> {
  private originalObject: OriginalType;

  constructor(obj: OriginalType) {
    this.originalObject = obj;
  }

  public get<Key extends keyof OriginalType>(key: Key) {
    const value = this.originalObject[key];
    if (typeof value === 'object') {
      return new Wrapper(value); // ok
    }
    return value;
  }
}

Playground