How to Use Type Checking in Deno: Simple Guide
Deno uses TypeScript by default, which provides built-in
type checking during development. You write your code with types, and Deno checks them automatically when you run or compile your scripts using deno run or deno check commands.Syntax
Deno uses TypeScript syntax for type checking. You declare types for variables, function parameters, and return values using simple annotations.
let name: string = "Alice";declares a string variable.function add(a: number, b: number): numberdeclares a function with number parameters and return type.interfacedefines custom types for objects.
typescript
let age: number = 30; function greet(name: string): string { return `Hello, ${name}!`; } interface User { id: number; name: string; } const user: User = { id: 1, name: "Bob" };
Example
This example shows how Deno checks types automatically. If you try to assign a wrong type, Deno will show an error before running.
typescript
function multiply(x: number, y: number): number { return x * y; } console.log(multiply(5, 4)); // Uncommenting the next line causes a type error // console.log(multiply("5", 4));
Output
20
Common Pitfalls
Common mistakes include ignoring type errors or mixing types incorrectly. For example, passing a string where a number is expected causes errors.
Also, forgetting to run deno run or deno check means you miss type checking.
typescript
function divide(a: number, b: number): number { return a / b; } // Wrong: passing string instead of number // console.log(divide("10", 2)); // Error // Correct usage: console.log(divide(10, 2));
Output
5
Quick Reference
| Concept | Syntax Example | Description |
|---|---|---|
| Variable Type | let count: number = 10; | Declares a variable with a number type |
| Function Parameter | function f(x: string): void {} | Function with typed parameter and no return |
| Interface | interface Person { name: string; age: number; } | Defines a custom object type |
| Type Error | let x: number = "text"; | Assigning wrong type causes error |
| Run Type Check | deno check file.ts | Checks types without running code |
Key Takeaways
Deno uses TypeScript syntax for built-in type checking.
Run your code with 'deno run' or check types with 'deno check'.
Always declare types for variables and functions to catch errors early.
Type errors prevent code from running until fixed.
Use interfaces to define structured object types clearly.