Is it possible to contain a type guard within a function as shown below?
function assertArray(value: any): void {
if (!Array.isArray(value)) {
throw "Not an array"
}
}
// This doesn't work
function example1(value: string | []) {
assertArray(value)
return value.join('')
}
// But this does work
function example2(value: string | []) {
if (!Array.isArray(value)) {
throw "Not an array"
}
return value.join('')
}
The use case is quite straightforward. I want to include runtime assertions, and I prefer to encapsulate the logic without creating new variables. I am aware that I could const x = assertArray(y)
, but why can't I simply do assertArray(y)
?