In my software, I have an interface that serves as a base for other types. To simplify things for this discussion, let's focus on one specific aspect.
This interface includes an optional method called getColor
.
I am creating an object that implements this interface and statically defines the method getColor
, ensuring it is always available.
However, when attempting to use ITEM_CONFIG.getColor
, TypeScript raises an error stating "Cannot invoke an object which is possibly 'undefined'.".
How can I instruct TypeScript to acknowledge that in this context, the method is guaranteed to be present?
interface NodeConfig<T extends object | AnyItemData> {
getColor?: (data: T) => string;
}
export const ITEM_CONFIG: NodeConfig<ItemData> = {
getColor: (data) => '#ff0000',
};