Optional obj: anyThe object to check for trouble awareness. Can be any type.
true if the object implements TroubleAware interface, false otherwise.
When this function returns true, TypeScript will narrow the type of obj
to TroubleAware in the current scope.
// Basic type guard usage
function processModel(model: IKosDataModel) {
if (isTroubleAware(model)) {
// TypeScript now knows model has troubles property
console.log(`Found ${model.troubles.length} troubles`);
console.log(`Trouble status: ${model.troubleStatus}`);
} else {
console.log('Model is not trouble-aware');
}
}
// Using with React hooks for conditional trouble handling
const TroubleDisplay: React.FC<{ model: IKosDataModel }> = ({ model }) => {
if (!isTroubleAware(model)) {
return <div>No trouble tracking available</div>;
}
// Safe to access trouble properties here
const criticalTroubles = model.troubles.filter(t => t.rank > 8);
const troubleTypes = Object.keys(model.troublesByType);
return (
<div>
<h3>Trouble Status: {model.troubleStatus}</h3>
<p>Critical issues: {criticalTroubles.length}</p>
<p>Types: {troubleTypes.join(', ')}</p>
</div>
);
};
// Filtering trouble-aware models from a collection
const models: IKosDataModel[] = getAllModels();
const troubleAwareModels = models.filter(isTroubleAware);
// TypeScript knows troubleAwareModels is TroubleAware[]
troubleAwareModels.forEach(model => {
const troublesByType = model.troublesByType;
Object.entries(troublesByType).forEach(([type, troubles]) => {
console.log(`Type ${type}: ${troubles.length} troubles`);
});
});
// Early return pattern for non-trouble-aware models
function calculateTroubleSeverity(model: any): number {
if (!isTroubleAware(model)) {
return 0; // No troubles means no severity
}
// Calculate weighted severity based on trouble ranks
return model.troubles.reduce((total, trouble) => {
return total + (trouble.rank * (trouble.deferred ? 0.5 : 1));
}, 0);
}
troubles is specifically an Array instance, not just array-liketroublesByType property must be an object (not null or undefined)
Type guard function to check if an object implements the TroubleAware interface.
This function performs runtime validation to determine whether a given object has the necessary properties and structure to be considered trouble-aware. It checks for the presence of both the
troublesarray andtroublesByTypeobject, which are required by the TroubleAware interface.