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:
This tutorial is beginner-friendly. A basic knowledge of JavaScript would be beneficial but is not strictly necessary.
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;
TypeScript includes several data types, including:
boolean
, number
, string
, null
, undefined
, symbol
, and void
.enum
, class
, interface
, array
, and tuple
.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;
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" };
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
let value: any = "John Doe";
let length: number = (value as string).length;
console.log(length); // Output: 8
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
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.
number
and a variable of type boolean
in TypeScript.Solution:
typescript
let age: number = 25;
let isAdult: boolean = true;
any
.Solution:
typescript
let value: any = "Hello World";
let length: number = (value as string).length;
console.log(length); // Output: 11
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!