Is there a more elegant way for TypeScript to check if a value matches a specific type without actually invoking it, instead of the method described below?
Consider the following example:
import { OdbEventProcessorFunc } from "./OdbEventProcessor";
export function tviewEventProcessor() {
// some implementation here... doesn't matter for the question
}
// The current method:
function unused_just_for_type_check_of_the_function() {
// This line checks that the function 'tviewEventProcessor' is actually 'OdbEventProcessorFunc' and raises TS2322 error if it's not
const unused_just_for_type_check_of_the_function2: OdbEventProcessorFunc = tviewEventProcessor;
}
The existing code achieves the desired outcome, but I only use it in rare cases. Is there a better alternative?
Something like
typescript_please_check_that(tviewEventProcessor is OdbEventProcessorFunc )
Issues with the current approach:
- It's awkward and lengthy to write
- It generates additional code that may be bundled, even though it should be removed by tree shaking
Additional Q&A: Q: Why confirm the type this way instead of checking it on the caller side? A: By checking the type this way, when I modify the definition of 'OdbEventProcessorFunc,' I want IDE to point me to errors at the definition rather than at the callers of the function.