This code snippet defines a function for validating protocols and throwing an error if the input does not match the predefined protocols.
const validProtocols = ["https", "http"] as const
type AllProtocols = typeof validProtocols
type Protocol = AllProtocols[number]
function isProtocol(p: unknown): p is Protocol {
return typeof p === "string" && p in validProtocols
}
let parse = (p: string) => {
if (isProtocol(p))
return p
else
throw `${p} is not a protocol`
}
console.log(parse("https"))
Although the code compiles, there seems to be an issue with the last line as isProtocol(p)
returns false. Can you identify what might be causing this?
This code is designed to validate external input that is not controlled by the compiler, such as environment variables.