It appears that TypeScript automatically recognizes the type of the element you entered (CustomText
) because it is statically defined in your code. If the type had been dynamic, TypeScript would have raised an error.
For instance:
const getElem = () => {
if(Math.floor((Math.random() * 10) + 1)%2)
{
const x : TitleElement = { name: 'title', children: 'x' };
return x;
}
else {
const x : CustomText = { bold: false };
return x;
}
}
type CustomText = {
bold: boolean;
};
type TitleElement = { name: 'title'; children: string };
type Element2 = TitleElement | CustomText;
let el: Element2 = getElem();
if (!el.bold) {
console.log("does not have bold")
}
if (!el.name) { // <- compiler error
console.log("does not have type")
}
Playground
The purpose of Union is to allow properties from all union members. You can access any property present in both CustomText
and TitleElement
. TypeScript will throw an error if you attempt something like the following, as it violates this rule.
type CustomText = {
bold: boolean;
both : string;
};
type TitleElement = { name: 'title'; children: string, both : string; };
type Element2 = TitleElement | CustomText;
const el: Element2 = {
bold: true,children: 'sing'
}
if (!el.bold) {
console.log("does not have bold")
}
if (!el.name) { // <- compiler error
console.log("does not have type")
}
if (!el.both) { // <- compiler error
console.log("does not have type")
}
This occurs because TypeScript is unsure of the type of Element2
, preventing access to properties not common to both types.
Playground