Consider the code snippet below:
const publicPath: string | undefined = config.output && config.output.publicPath
invariant(publicPath, "No publicPath for config: ${config}")
// declare const publicPath: string // error
After the invariant
function is called, we can be certain that publicPath
will not be empty (the program will stop if it is). How can we communicate this to TypeScript?
Even the following approach doesn't yield the desired result:
function invariant<T>(s: T | undefined | null, msg): s is T | never {
if (!s)
throw new Error(msg)
return true
}
const publicPath: string | undefined = '/* ... */'
invariant(publicPath, "No publicPath for config: ${config}")
// publicPath is still a string