0
0
DenoHow-ToBeginner ยท 3 min read

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): number declares a function with number parameters and return type.
  • interface defines 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

ConceptSyntax ExampleDescription
Variable Typelet count: number = 10;Declares a variable with a number type
Function Parameterfunction f(x: string): void {}Function with typed parameter and no return
Interfaceinterface Person { name: string; age: number; }Defines a custom object type
Type Errorlet x: number = "text";Assigning wrong type causes error
Run Type Checkdeno check file.tsChecks 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.