Hi everybody, good morning post lovers. I hope you are good today. Today I'm gonna explain the Typescript programming language's basic features. I like to write Typescript. Actually Typescript syntax almost similar to C# programming languages syntax.
Have you ever visited the Playground 👉 If you say no 🖱 to the Url PlayGround
What is TypeScript?
TypeScript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is designed for the development of large applications and transcompiles to JavaScript.[4] As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs. More detail
TypeScript is an open-source language that builds on JavaScript, one of the world’s most used tools, by adding static type definitions. More detail
A few pros
- Easier to read and understand
- All the benefits of ES6 (ECMAScript 6)
- Rich IDE Support
- Support interface and static
Basic data types with samples
- String
Represent a sequence of Unicode characters.
let userName : string
userName = "burak";
console.log(userName);
or
let userName : string = "burak"
console.log(userName);
- Boolean (true or false)
Represent logical value.
let isCheckTermsOfCondition : boolean = false;
- Number (floating points, bignumbers)
Double precision 64-bit floating-point values. It can be used to represent both, integers and fractions
let age : number = 30;
backtick with embedded expression
let firstName : string = "Burak"
let lastName : string = "Seyhan"
let age : number = 30
let result : string = `Hi, I'm ${firstName} ${lastName}. I'm ${age} years old.`
console.log(result)
console.log("Hi, I'm " + firstName + " " + lastName + "." + "I'm " + age + "years old.")
enum declaration
enum Gender{
Male = 0,
Female
}
console.log(Gender.Female)
console.log(Gender[0])
Tuple declaration
Tuple can contain two values of different data types.
var brands: [number, string] = [1, "Apple"]
Let's define a tuple array. Tuple working like index [index].
var cars: [number, string][];
cars = [[1, "Polo"], [2, "Tiguan"], [3, "T-Roc"]];
console.log(cars[0])
console.log(cars[1])
console.log(cars[2])
Declare functions and arrays
function function_name(){
}
function function_name(datatypeName:datatype){
}
function function_name(datatypeName:datatype) : return type{
}
array declarations
// var names : string[] = [] empty string array
Let's create functions with names array.
var names : string[] = ["Burak", "Burak_1", "Burak_2", "Burak_3"]
function getNames(){
for(var n of names)
console.log(n)
}
getNames();
After that, I added new names with the push method.
names.push("Client");
names.push("Client_1");
Then call the getNames() method again
Declaration of comment
//code line
/*
code blocks
*/
Class, Constructor, and Function
- Class declaration
In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior. More detail
Like C#, if you wanna class objects you have to instantiate with new keyword.
class Catalog{
name : string = ""
description : string = ""
}
var catalog = new Catalog();
catalog.name = "Electronic";
catalog.description = "...";
console.log(`CatalogName: ${catalog.name} Description: ${catalog.description}`);
Constructor declaration
In class-based object-oriented programming, a constructor (abbreviation: ctor)* is a special type of subroutine called to create an object. More detail
Thus, you can create multiple constructors.
class Catalog{
name : string
description : string
constructor(name: string, description: string){
this.name = name;
this.description = description;
}
}
var catalog = new Catalog("Cloths","...");
console.log(`CatalogName: ${catalog.name} Description: ${catalog.description}`);
- Function declaration
class Product{
name : string
unitsInStock : number
constructor(name: string, unitsInStock: number){
this.name = name;
this.unitsInStock = unitsInStock;
}
getInformation(){
console.log(`Product Name: ${this.name}
UnitsInStock: ${this.unitsInStock}`);
}
}
var product = new Product("Macbook 13.inc", 34);
product.getInformation();
Inheritance
In TypeScript, we can use common object-oriented patterns. One of the most fundamental patterns in class-based programming is being able to extend existing classes to create new ones using inheritance. More detail
// base class
class Fligth{
protected from : string
protected to : string
protected flightnumber : string
protected numberOfPassenger : number
constructor(from:string, to:string,
number: string,passenger: number){
this.from = from;
this.to = to;
this.flightnumber = number;
this.numberOfPassenger = passenger
}
}
class XAirlines extends Fligth{
fligthDetails(){
console.log(`From ${this.from}}, To ${this.to},
Fligth Number ${this.flightnumber} NumberOfPassenger ${this.numberOfPassenger}
Delay ${this.isDelay}`);
}
}
class ABCAirlines extends Fligth{
fligthDetails(){
console.log(`From ${this.from}}, To ${this.to},
Fligth Number ${this.flightnumber} NumberOfPassenger ${this.numberOfPassenger}
Delay ${this.isDelay}`);
}
}
class WinterAirlines extends Fligth{
isDelay = true
constructor(data: {from:string, to:string, number: string,passenger: number}){
super(data.from, data.to, data.number, data.passenger);
}
fligthDetails(){
console.log(`From ${this.from}}, To ${this.to},
Fligth Number ${this.flightnumber} NumberOfPassenger ${this.numberOfPassenger}
Delay ${super.isDelay}`);
}
}
var xairlines = new XAirlines("Istanbul","Berlin","23SD98",135);
xairlines.fligthDetails();
var abcAirlines = new ABCAirlines("Ankara","Holland","3311BS",70);
abcAirlines.fligthDetails();
var winterAirlines = new WinterAirlines({from:"Istanbul",to:"Poland",number:"2311BS",passenger:223});
winterAirlines.fligthDetails();
Interface declaration
interface UserService{
emailAddress:string
firstName : string
lastName :string
Login(email:string) : User
}
class User **implements** UserService {
emailAddress: string;
firstName: string;
lastName!: string;
constructor(email: string, firstName: string, lastName: string){
this.emailAddress = email
this.firstName = firstName
this.lastName = lastName
}
Login(email: string): User {
return new User(email, this.firstName, this.lastName);
}
}
var user = new User("burakseyhan8@gmail.com","burak","seyhan");
console.log(`Email Address ${user.emailAddress} FirstName ${user.firstName} LastName ${user.lastName}`);
Generics
Typescript also has generic like C#. Here is the key DRY so if you need the same method in a different class you should use the base interface.
Here is the definition of generics
interface interfaceName<T> {
// ...
}
interface interfaceName<T,L> {
// ...
}
Let's write some examples.
interface Repository<T> {
GetItems(): T[];
GetItem(id: number): T;
Remove(id: number): boolean;
Save(item: T): T;
}
declare class Person {
//properties here
}
declare class PersonService implements Repository<Person> {
GetItems() {
throw new Error("Method not implemented.");
}
GetItem(id) {
throw new Error("Method not implemented.");
}
Remove(id) {
throw new Error("Method not implemented.");
}
Save(item) {
throw new Error("Method not implemented.");
}
}
Thank you for reading 🧐
Top comments (0)