Run ❯
Get your
own Node
server
❯
Run Code
Ctrl+Alt+R
Change Orientation
Ctrl+Alt+O
Change Theme
Ctrl+Alt+D
Go to Spaces
Ctrl+Alt+P
"use strict"; // @ts-check // Type Inference: Type Guards and Control Flow Analysis (JS demo with JSDoc) // Example 1: typeof guard narrows string | number at runtime /** * @param {string | number} value */ function processValue(value) { if (typeof value === "string") { // Narrowed to string console.log(value.toUpperCase()); } else { // Narrowed to number console.log(value.toFixed(2)); } } processValue("hello"); processValue(12.345); // Example 2: Discriminated unions with a 'kind' property /** * @typedef {{ kind: "circle"; radius: number }} Circle * @typedef {{ kind: "square"; size: number }} Square * @typedef {Circle | Square} Shape */ /** * @param {Shape} shape * @returns {number} */ function area(shape) { switch (shape.kind) { case "circle": return Math.PI * shape.radius ** 2; case "square": return shape.size ** 2; } } console.log(area({ kind: "circle", radius: 2 })); console.log(area({ kind: "square", size: 3 }));
HELLO 12.35 12.566370614359172 9