首页 > 解决方案 > 在打字稿中选择一种交叉类型

问题描述

我发现自己处于以下情况:

有了一个 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"}

标签: typescript

解决方案


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));

推荐阅读