DeltaTango
DeltaTango

Reputation: 891

Typescript property type same as property which has multiple types

In my data store, I have two properties

data, backupData

I am trying to define that backupData must be of the same type as data.

However,

class ClassC{
   data: InterfaceA | InterfaceB
   backupData: InterfaceA | InterfaceB 
}

does not ensure that backup is the SAME type as data.

Should backupData be of type any or is there a way to write this?


As a follow up for others who come across this, the solution worked using the answer below by doing:

class ClassC<T>{
   data: T;
   backupData: T;
}

Upvotes: 2

Views: 984

Answers (1)

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

I think you need to solve this with a generic type.

interface A {
  foo: string;
}

interface B {
  bar: string;
}

class MyClass<T extends A | B> {
  data: T;
  backupData: T;
}

const example1: MyClass<A> = {
  data: { foo: 'foo' },
  backupData: { foo: 'foo' }
}

const example2: MyClass<B> = {
  data: { foo: 'foo' }, // compiler error
  backupData: { bar: 'bar' }
}

Upvotes: 3

Related Questions