Implement five type guard functions. In TypeScript, a type guard is a function whose return type is x is T — a type predicate that narrows the type of a variable in the surrounding scope:
function isString(x: unknown): x is string {
return typeof x === 'string';
}
const value: unknown = 'hello';
if (isString(value)) {
value.toUpperCase(); // TypeScript knows value is string here ✅
}| Guard | Passes for | Fails for |
|---|---|---|
isString | 'hello' | 42, null |
isNumber | 42 | '42', NaN |
isArray | [], [1,2,3] | {}, null |
isNullish | null, undefined | 0, '', false |
isObject | { a: 1 } | [], null, functions |
isNumber must return false for NaN (it is typeof 'number' but not a valid number)isObject must return false for arrays (they are objects but not plain objects)isObject must return false for null (typeof null === 'object' is JS's famous bug)Sample tests