TypeScript / TypeScript Basics

Declaring Variables and Working with Data Types

In this tutorial, you will learn about declaring variables and using different data types in TypeScript. We will also cover the basics of type assertions and interface types.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers the fundamental concepts of TypeScript, including type annotations, variables, and basic syntax.

Introduction

Our goal in this tutorial is to introduce you to the basics of declaring variables and working with different data types in TypeScript. TypeScript is a strongly typed, object-oriented, compiled language.

By the end of this tutorial, you will learn:

  • How to declare variables in TypeScript
  • The different data types available in TypeScript
  • How to use type assertions and interface types

This tutorial is beginner-friendly. A basic knowledge of JavaScript would be beneficial but is not strictly necessary.

Step-by-Step Guide

Declaring Variables

In TypeScript, you can declare variables using var, let, and const keywords, similar to modern JavaScript.

let name: string = "John Doe";
const age: number = 30;
var isAdult: boolean = true;

Data Types

TypeScript includes several data types, including:

  • Basic types: boolean, number, string, null, undefined, symbol, and void.
  • User-defined types: enum, class, interface, array, and tuple.

Type Assertions

TypeScript allows you to override its inferred and analyze your code similar to other statically typed languages. This is known as "Type Assertions". Type assertions have two forms.

// angle-bracket syntax
let str: any = "I am a string";
let strLength: number = (<string>str).length;

// as-syntax
let str: any = "I am a string";
let strLength: number = (str as string).length;

Interface Types

Interfaces are a powerful way to define contracts within your code and contracts with code outside of your project.

interface Person {
  firstName: string;
  lastName: string;
}

// This object is of type 'Person'
let aPerson: Person = { firstName: "John", lastName: "Doe" };

Code Examples

Example 1: Declaring Variables

let isDone: boolean = false; // Boolean type
let age: number = 20; // Number type
let fullName: string = "John Doe"; // String type

console.log(isDone); // Output: false
console.log(age); // Output: 20
console.log(fullName); // Output: John Doe

Example 2: Type Assertions

let value: any = "John Doe";
let length: number = (value as string).length;

console.log(length); // Output: 8

Example 3: Interface Types

interface Person {
  firstName: string;
  lastName: string;
}

let aPerson: Person = { firstName: "John", lastName: "Doe" };

console.log(aPerson.firstName); // Output: John
console.log(aPerson.lastName); // Output: Doe

Summary

In this tutorial, we've learned about declaring variables and using different data types in TypeScript. We also covered how to use type assertions and interface types. The next step would be learning about classes and objects in TypeScript. You can refer to the official TypeScript documentation for more information.

Practice Exercises

  1. Exercise: Declare a variable of type number and a variable of type boolean in TypeScript.

Solution:
typescript let age: number = 25; let isAdult: boolean = true;

  1. Exercise: Use type assertion to find the length of a string stored in a variable of type any.

Solution:
typescript let value: any = "Hello World"; let length: number = (value as string).length; console.log(length); // Output: 11

  1. Exercise: Create an interface for a Car object with model, year, and color properties.

Solution:
```typescript
interface Car {
model: string;
year: number;
color: string;
}

let myCar: Car = { model: "Toyota", year: 2015, color: "red" };
console.log(myCar); // Output: { model: 'Toyota', year: 2015, color: 'red' }
```

Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help