首页 > 解决方案 > 从对象中提取子类型

问题描述

现在是否可以在运行时仅提取属性的子集。可能使用了一些花哨的装饰器或元数据库?

function only<IN extends OUT, OUT>(object: IN): OUT {
  const result: OUT = {};
  for (const key of getKeysOf<OUT>()) {
    result[key] = object[key];
  }
  return result;
}

怎么可能写出这样的函数getKeysOf

例子:

interface Foo {
  x: string;
}

interface Bar extends Foo {
  y: string;
}

const foo = only<Bar, Foo>({x: 'x', y: 'y'});

// foo should contain ONLY properties of `Foo`, not `Bar`
// -> foo == {'x'} should hold

标签: typescript

解决方案


我们不必深入研究 Typescript,但我们可以通过简单地使用类来实现与您所要求的非常相似的东西:

class Foo {
    x: string = '';
}

class Bar implements Foo {
    x: string = '';
    y: string = '';
}

class Baz {
    z: string = '';
}

function only<T, K extends T>(a: T, b: K): T {
    for (let key in a) {
        a[key] = b[key]
    }
    return a
}

const foo = only(new Foo(), new Bar()); // works
const fooToo = only(new Baz(), new Bar()); // errors out

如果它们具有相似的键,上述内容也适用于普通对象。

重要的是要记住类型在运行时被剥离,所以我们不能简单地使用OUTin <IN extends OUT, OUT>。我们实际上必须提供OUTJavascript 可以与之交互的东西。


推荐阅读