typescript - 从对象中提取子类型
问题描述
现在是否可以在运行时仅提取属性的子集。可能使用了一些花哨的装饰器或元数据库?
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,但我们可以通过简单地使用类来实现与您所要求的非常相似的东西:
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
如果它们具有相似的键,上述内容也适用于普通对象。
重要的是要记住类型在运行时被剥离,所以我们不能简单地使用OUT
in <IN extends OUT, OUT>
。我们实际上必须提供OUT
Javascript 可以与之交互的东西。
推荐阅读
- c++ - Chase-lev deque 中的原子存储
- excel - 将数据框写入现有 Excel 文件中的多个工作表。打开 excel 文件时出现“我们发现 X.xlsx 中的某些内容存在问题”
- docker - VMware Photon - Clair 无法扫描 vSphere 上的 Photon 容器漏洞
- shell - 将部分 getopts 共享为函数
- apache-spark - Spark-Streaming 最早因 kafka 起始偏移而挂起(Kafka 2,spark 2.4.3)
- python - 在“with”语句中检索代码
- pytorch - Pytorch张量乘法与浮点张量给出错误答案
- git - Git无法在http代理后面的dockerfile中工作
- html - min-height 导致填充被忽略
- javascript - React 中进出 CSS 转换的不同延迟