Suppose the following:
const handleParse = (arg: { value: boolean } | null) => {
if (!arg?.value) {
throw new Error(`\`arg\` is null`)
}
return arg.value;
}
Here, Typescript knows inline, that the returned arg.value
will always be defined.
However, I'm trying to refactor the thrown error to a helper method, but it's throwing an error:
const checkDependency = (dependency: any) => {
if (!dependency) {
throw new Error(`\`dependency\` is null`)
}
}
const handleParse = (arg: { value: boolean } | null) => {
checkDependency(arg)
return arg.value;
// ^^^ 'arg' is possible null
}
How can I accomplish this? I've tried playing around with the return type, but to no avail:
const checkDependency = (dependency: any): Error | void => {
if (!dependency) {
throw new Error(`\`arg\` is null`)
}
return;
}
You can use a type assertion function for that combined with a type parameter we combine with null
:
function checkDependency<T>(arg: T | null): asserts arg is T {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^
if (arg === null) {
throw new Error(`\`arg\` is null`);
}
}
Here's your example using that:
const handleParse = (arg: { value: boolean } | null) => {
checkDependency(arg);
return arg.value; // <== No error
};
Full example on the Playground
Type assertion functions were added in TypeScript v3.7. They're similar to type predicates, but they do exactly what you describe: Indicate that if the function doesn't throw, the type is as the function asserts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With