EasyJavaScriptTypeScript
Narrowing — typeof, instanceof & in
TypeScriptNarrowingType Guards
TypeScript uses control flow analysis to narrow types within branches. Implement describe(value) that returns a string describing its input:
| Input | Output |
|---|---|
| string | "string: {value}" |
| number (non-NaN) | "number: {value}" |
Date instance | "date: {value.toISOString()}" |
object with name property | "named: {value.name}" |
| anything else | "unknown" |
Order matters — check from most specific to least specific.
Examples
describe("hello")→"string: hello"describe(42)→"number: 42"describe(new Date("2024-01-01"))→"date: 2024-01-01T00:00:00.000Z"describe({ name: "Alice" })→"named: Alice"
Sample tests
Test #1string value
Input: ["raw","hello"]
Output: "string: hello"
Test #2number value
Input: ["raw",42]
Output: "number: 42"
Test #3Date instance
Input: ["date","2024-01-01T00:00:00.000Z"]
Output: "date: 2024-01-01T00:00:00.000Z"
Test #4object with name
Input: ["raw",{"name":"Alice"}]
Output: "named: Alice"
Test #5null is unknown
Input: ["raw",null]
Output: "unknown"