There exist numerous approaches to tackle this issue.
To access the properties, there are two methods:
- Simply refrain from destructuring the object
export function Inputfield(props:(
{
isText: true,
children:string
} | {
isText: false,
children:number
}
)) {
if (props.isText === true) {
let data:string = props.children
} else if (props.isText === false) {
let data:number = props.children
}
}
- Destructure it after the if statement
export function Inputfield(props:(
{
isText: true,
children:string
} | {
isText: false,
children:number
}
)) {
if (props.isText === true) {
let {children} = props
let data:string = children
} else if (props.isText === false) {
let {children} = props
let data:number = children
}
}
When applying default values, two different outcomes can be achieved:
- Default values for singular properties
type props_type = {
isText: true,
children:string
} | {
isText: false,
children:number
}
export function Inputfield(_props:(
Partial<props_type>
)) {
const props = {
isText: true,
children: "",
..._props
} as props_type
if (props.isText === true) {
let data:string = props.children
} else if (props.isText === false) {
let data:number = props.children
}
}
This can also be elaborated with additional conditional assignments if undefined
type props_type = {
isText: true,
children:string
} | {
isText: false,
children:number
}
function Inputfield(_props:(
Partial<props_type>
)) {
if (_props.isText == undefined) _props.isText = true;
if (_props.children == undefined) _props.children = "";
const props = _props as props_type;
if (props.isText === true) {
let data:string = props.children
} else if (props.isText === false) {
let data:number = props.children
}
}
- A default object
export function Inputfield(props:(
{
isText: true,
children:string
} | {
isText: false,
children:number
}
)={
isText:true,
children:"",
}) {
if (props.isText === true) {
let data:string = props.children
data;
} else if (props.isText === false) {
let data:number = props.children
data;
}
}
By using defaults as individual values, not assigning a property will result in the default value being used. When providing a default object, only when no input object is provided, the default will apply.
It is possible to mix together the methods of accessing properties and applying default values as necessary.