typescript - 在打字稿中选择一种交叉类型
问题描述
我发现自己处于以下情况:
有了一个 type 的变量A
,我将它传递给一个返回 type 值的 API A & B
。然后,我必须将此返回值发布到 HTTP 端点,该端点需要类型为A
.
interface A {
name: string;
}
interface B {
type: string;
}
function api(arg: A): A & B {
return { name: arg.name, type: 'Blah' };
}
const x: A = { name: 'Foo' };
const y: A & B = api(x);
const z: A = y;
// Simulate HTTP call with payload z of type A
console.log(JSON.stringify(z));
输出是{"name":"Foo","type":"Blah"}
。虽然z
是 type A
,但payload仍然包含B
's 字段。
如何删除其中一种交集类型(B)并仅保留类型A
以使输出为{"name":"Foo"}
?
解决方案
Titian很好地解释了这一点,但不幸的是接口是编译时组件而不是运行时,所以这些情况很难解释。使用他们的解决方案,您可以根据您的情况对其进行调整以获得类似
function extract<T>(properties: Record<keyof T, true>) {
return function <TActual extends T>(value: TActual): T {
const result = {} as T;
for (const property of Object.keys(properties) as Array<keyof T>) {
result[property] = value[property];
}
return result;
};
}
const extractA = extract<A>({
name: true,
});
// { name: 'Foo' }
console.log(extractA(z));
推荐阅读
- django - 未找到没有参数的“user_logout”反向
- django - Django methodSerializer 不返回绝对图像 url
- flutter - 如何在颤动中选择默认单选按钮
- azure - 缺少必填字段时,是否可以强制 Azure API 管理返回 400 而不是 404?
- python - 在 numpy 数组中包含不同形状的信息的最佳方法?
- ruby-on-rails - Rails 18n French:使用带重音的单词时出现特殊字符
- java - 如何迭代思想 JLabel 对象以将图标添加到特定对象
- exceed - 问:保存打开文本是否超出窗口大小和位置?
- abap - 具有不同域的字段的内部连接
- javascript - 同时部署 Node.js Restfull API 和 Vue.js 应用