Let's understand different data types in typescript.
Just like any other scripting language TypeScript also support almost all data types, you find typescript data types are very similar to JavaScript and C#, here we explain few regularly used data types in typescript program development.
Assuming you are already familiar with JavaScript data type or C# data types , so we focus more on whatever new in typescript.
Here are some of the commonly used typescript data types
let companyName:string = "WebTrainingRoom";
let totalCount: number = 100; let foodPrice: number = 150.40;
let isComplete: boolean = true; let isDelayed: boolean = false;
when we declare a variable as any, we can assign any type of value other than the type was initialized.
let anyVar: any = "This is a string value"; anyVar = 100; anyVar = true;
let colors: string[] = ['Red', 'Blue', 'Green','White']; let colorList: Array<string>; colorList = ['Red', 'Blue', 'Green','White'];
var employee: [number, string, date] = [1, "Bill", ""];
function Welcome(): void { console.log('Hi!') } let w_message: void = Welcome();
Actually, there is no meaning to assign void to a variable, still here is how you can do that!
let someVar: void = undefined;
let nValues: null = null;
Like any other object oriented programming language, in typescript, we can define custom data types like examples below.
Class is common data type often we create as business object, like "Student" is the business object in this example.
class Student { studId: number; FirstName: string; LastName: string; FullName: string; constructor(id: number, fullname: string) { this.FullName = fullname; this.studId = number; } getTotalMarks() : number { totalMarks: number = 680; return totalMarks; } }
In typescript, we can define interface, but here we can have optional properties in typescript interface, which was not possible in c# interface definition.
Optional members are marked with question mark like Mobile?: number;
interface Person { FullName: string; Email?: string; Mobile?: number; City: string; } function createEmployee(people: Person): {FullName: string; Email: string; Mobile: number; City: string} { let newEmp = {FullName: "Ajay Balasari", Mobile: 98000001}; return newEmp; }
You may be interested to read following posts: