I attempted to instantiate an interface object with properties initialized from another object as follows:
id: data.reference.id
Even though the properties are compatible, the TypeScript compiler is throwing an error. I am confused about why this is happening and how to resolve it.
(you can find a link to test the code below)
// INTERFACES AND TYPES
type CategoryOne = 1
type CategoryTwo = 2
type Category = CategoryOne | CategoryTwo
interface ReferenceOne {
id: string,
type: CategoryOne
}
interface ReferenceTwo {
id: string,
type: CategoryTwo
}
type Reference = ReferenceOne | Â ReferenceTwo
// DIRECT INIT
let reference_OK: Reference = { // works here
id: '1',
type: 1
}
// INIT FROM DATA
interface Data {
reference: {
id: string,
type: Category
}
}
let data: Data = {
reference: {
id: '1',
type: 1
}
}
let reference_KO: Reference = { // <--- error occurs here
id: data.reference.id, // although the property is compatible
type: data.reference.type // yet the property is compatible
}
let param: Category = data.reference.type // == 1
let reference_KO2: Reference = { // <--- error occurs here
id: data.reference.id, // although the property is compatible
type: param // yet the property is compatible
}
param = 1 // == data.reference.type - same variable
let reference_OK2: Reference = { // <--- no error happens here
id: data.reference.id,
type: param
}
You can explore this code in TypeScript playground
[update] I have included a scenario where a new reference is created from a variable (reference_KO2 - variable initialized from a property of data - and reference_OK2 - same variable initialized with a constant)
There are two different behaviors observed with the same variable of a compatible type!