【问题标题】:How to fit an object with one interface to another interface?如何将具有一个接口的对象适配到另一个接口?
【发布时间】:2019-09-06 01:30:54
【问题描述】:

我有两个接口,ABBA 的扩展:

interface A {
    foo: string;
}

interface B extends A {
    bar: string;
}

另外,我有一个对象a 具有A 接口:

const a: A = {
    foo: "fooValue"
}

我需要构建一个函数,该函数根据接口A 的输入创建一个接口B 的新对象,并添加一个默认值。

我已经创建了一个:

function AtoB(a: A): B {
    return {
        ...a,
        bar: "defaultBarValue"
    };
}

但是这个函数对B接口了解太多了。而一旦我更改了B 接口,我也需要一直更改此功能。

也许有人知道更多“TypeScript”方法来构建这样的功能?

也许我需要使用类来执行此操作?

【问题讨论】:

  • 这种方法有什么问题?每当B 接口更改时,您将在编译时在AtoB 中收到类型错误,并且您知道在尝试运行它之前要修复它吗?是不是只想定义一次B接口和值?
  • 你的情况是什么?
  • @skovy,是的,我想在一个地方定义B接口和默认值。

标签: typescript


【解决方案1】:

我想在一处定义B接口和默认值

这对于一个类来说可能是一个很好的用例。当然,这可以通过多种不同的方式完成,我对您的用例了解不多,但这是一种可能性:

class A {
  foo: string;

  constructor(a: A) {
    this.foo = a.foo;
  }
}

class B extends A {
  bar: string = 'barDefault';
}

function AtoB(a: A): B {
  return new B(a);
}

我们现在有一个类层次结构,而不仅仅是接口,B 继承自 AA 定义了属性foo 以及一个构造函数,该构造函数接受A 类型的参数并从foo 复制值。

B 定义属性bar 并为其分配默认值。它没有明确定义构造函数。这意味着如果我们调用new B(),我们实际上是在调用类A 的构造函数。

Playground

【讨论】:

    【解决方案2】:

    您可以定义默认值,然后推断类型:

    interface A {
        foo: string;
    }
    
    const b = {
        bar: "defaultBarValue",
        baz: "anotherDefault"
    }
    
    type B = typeof b & A;
    
    const a: A = {
        foo: "fooValue"
    }
    
    function AtoB(a: A): B {
        return {
            ...a,
            ...b
        };
    }
    
    console.log(AtoB(a)) // {foo: "fooValue", bar: "defaultBarValue", baz: "anotherDefault"}
    

    TypeScript playground

    【讨论】:

      猜你喜欢
      • 2012-04-28
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 2012-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多