I've come across some answers such as this one, but the wording of my question doesn't return relevant results.
Consider the following:
type TNode = {
data: {
id: string;
} | {
tree: boolean;
treeName: string;
}
}
const nodes: TNode[] = [
{
data: {
id: '1',
}
},
{
data: {
id: '2',
}
},
{
data: {
id: '3',
tree: true,
treeName: 'retrieval',
}
}
]
This approach doesn't have TS complain, but it's not what I'm looking for. If I remove the property treeName: 'retrieval'
from the last object in nodes
, it should complain, saying that I've included tree
but I'm missing treeName
.
How can I achieve this?
Edit
The accepted answer worked for me, and so did the following approach, which I ended up using because I didn't want to add extra properties to my objects,
interface INodeBase {
id: string
}
interface INodeWithProps extends INodeBase {
tree: boolean;
treeName: string;
}
interface INodeWithOutProps extends INodeBase {
tree?: never;
treeName?: never;
}
type TNode = {
data: INodeWithProps | INodeWithOutProps
}
const nodes: TNode[] = [
{
data: {
id: '1',
}
},
{
data: {
id: '2',
}
},
{
data: {
id: '3',
tree: true,
treeName: 'retrieval',
}
},
{
data: {
id: '4',
tree: 'true', // error, 'treeName' is missing
}
},
]