I am working with a type called TreeItem
from a library and I need to add an optional onClick
function to this type (TreeItem2
).
Is there a way to extend the type without duplicating the entire declaration?
This is the code I have written so far:
// Type defined in library
interface TreeItem {
text?: string;
items?: TreeItem[];
// ...
};
// Extended type
type TreeItem2 = TreeItem & { items?: TreeItem2[], onClick?: () => void };
// Type usage
let item: TreeItem2 = {
text: "a",
onClick: () => {},
items: [{
text: "b",
onClick: () => {}, // Error
}]
};
Error message:
Type '{ text: string; onClick: () => void; }[]' is not assignable to type 'TreeItem[] & TreeItem2[]'.
Type '{ text: string; onClick: () => void; }[]' is not assignable to type 'TreeItem[]'.
Type '{ text: string; onClick: () => void; }' is not assignable to type 'TreeItem'.
Object literal may only specify known properties, and 'onClick' does not exist in type 'TreeItem'.