I have an interface Base, which interfaces A and B extend, and A and B both have properties that are unique and don't exist in the other. In my code, I have some data that will change depending on the type:
interface Base {
basicProperty: any,
basicProperty2: any
}
interface A extends Base {
aSpecificProperty: any
}
interface B extends Base {
bSpecificProperty: any
}
function(type): A | B {
const data: A | B = {
basicProperty: 1,
basicProperty2: 2
}
if (type === 'A') {
// Data should be type A
data.aSpecificProperty = 3;
} else if (type === 'B') {
// Data should be type B
data.bSpecificProperty = 3;
}
return data;
}
Is there any way to accomplish this without TypeScript complaining about the type not containing the right properties? Or, is there a way to reassign/specify the type of data from A | B to A or B?