Typescript相交类型转换为构成相交的类型之一

时间:2018-12-03 21:36:45

标签: javascript typescript

我希望有人可以帮助我找到一种干净的方法来实现这一目标。

我有两个这样的界面

interface A {
  prop1: string
  prop2: string
}

interface B {
  prop2: string
  prop3: string
}

还有这样的路口

myIntersection: A & B

我希望能够根据条件将此交集类型转换为A或B

let whatIWant: any = {}
if(myCondition)
  whatIWant = myIntersection as A
else
  whatIWant = myIntersection as B

当我这样做时,没有任何错误,但是新对象仍然包含相交对象的所有属性。有没有一种干净简单的方法可以做到这一点?

这对我造成的问题是我想将whatIWant对象另存为图像上的元数据,因此我需要剥离所有我尝试转换为该类型的属性。 / p>

2 个答案:

答案 0 :(得分:1)

使用类而不是接口应该做您想要的。接口仅描述对象具有的属性,而不描述对象不具有的属性,因此最简单的方法是将所需的属性复制到新对象。在不了解您的实际结构的情况下,我可能会执行以下操作:

// replace myIntersection with a base interface
interface MyData {
    prop1: string
    prop2: string
    prop3: string
}

// turn A and B into classes with constructors that take a MyData object
class A {
    prop1: string
    prop2: string
    constructor (data: MyData) {
        this.prop1 = data.prop1
        this.prop2 = data.prop2
    }
}
class B {
    prop2: string
    prop3: string
    constructor (data: MyData) {
        this.prop2 = data.prop2
        this.prop3 = data.prop3
    }
}

// Then initialize a new object based on your condition
const whatIWant = myCondition ? new A(myDataObject) : new B(myDataObject)

答案 1 :(得分:0)

好吧,我找到了另一种方法。我不会将其标记为已接受的答案,因为可能会有更好的方法。我选择使用类而不是接口,并使用复制构造函数从交集类型创建新对象。

示例

class A {
    prop1: string
    prop2: string
    constructor(obj: A)
    {
        this.prop1 = obj.prop1
        this.prop2 = obj.prop2
    }
}

class B {
    prop2: string
    prop3: string
    constructor(obj: B)
    {
        this.prop2 = obj.prop2
        this.prop3 = obj.prop3
    }
}

myIntersection: A & B

let whatIWant: any = {}
if(myCondition)
  whatIWant = new A(myIntersection)
else
  whatIWant = new B(myIntersection)

这对我有用。我只是希望有一种更清洁的方式来做到这一点