Note: I am new to using typescript. Before asking this question, I made sure to go through the documentation on advanced types and type guards. Additionally, I looked into several related questions on Stack Overflow such as user defined type guards [typescript], and How to write a user defined type guard for "string" | "literal" | "types"?)
The closest question to mine is the latter one where there is a custom type with a literal value (in this case string
, but it could also apply to number
) like:
type Format = 'JSON' | 'CSV' | 'XML'
In that question, the user enquires about utilizing typescript's keyof
keyword and @Ryan Cavanaugh's solution involves converting the type from a literal
to an interface
and checking the keys of the interface:
// copied from the answer for reference
interface McuParams {
foo, bar, baz;
}
function isKeyOfMcuParams(x: string): x is keyof McuParams {
switch (x) {
case 'foo':
case 'bar':
case 'baz':
return true;
default:
return false;
}
}
My question pertains specifically to whether it is possible to create user defined type guards using the type itself like so:
const isFormat = (maybe:String|Format): maybe is Format => /* something goes here */
To my understanding, the following approaches do not work (replacing just /* something goes here */
):
// 1
/*
* According to the documentation, "The right side of instanceof needs to
* be a constructor function" but we are dealing with a literal
*/
maybe instaceof Format
//2
/* As per the documentation, "typename" must be "number",
* "string", "boolean", or "symbol"
*/
typeof maybe === 'format'
//3
/* unsure */
(<Format>maybe)
So, is @Ryan Cavanaugh's solution the only feasible option? It appears quite lengthy...