我发现自己处于以下情况:
具有类型变量A
,我将其传递给API,该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
是类型A
,但有效负载仍包含B
的字段。
如何删除交集类型(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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句