Friday, August 4, 2017

Basic Types In Typescript


Typescript have same basic types as in javascript along with new enum type added in typescript.

Boolean

Boolean represents a logical entity and can have two values: true, and false.
E.g. let isValid: boolean = false;

Number
As in JavaScript,typescript has only one type of numbers. Numbers can be written with, or without decimals:
E.g. let decimal: number = 6;

String
String uses double quotes (") or single quotes (') to surround string data.
E.g. let firstname: string = "Naren"
let city: string = 'Pune'



We can also use Template strings which can span multiple lines and have embedded expressions. These strings are surrounded by the backtick/backquote (`) character, and embedded expressions are of the form ${ expr }.

let firstname: string = "Naren" let city: string = "Pune" let country: string = "India" let sentence: string = `Hello, My name is ${firstname}. I live in ${city + ", " + country}.` console.log(sentence)

=> This outputs following on console
Hello, My name is Naren. I live in Pune, India.


This is equivalent to declaring it in regular javascript as below:
let sentence: string = "Hello, My name is " + firstname + ".\n\n" + " I live in " + city + ", " + country + "."


Array
Array is a collection of values of the same data type.
Array can be created in two types
  1. let myarray: number[] = [1, 2, 3];
  2. using a generic array type, Array<elemType>:
let myarray: Array<number> = [1, 2, 3];

E.g.Following are valid array declarations
let myarr : string[];
myarr = ["1","2","3","4"]
let arr_names: number[] = new Array(4)
Or let arr_names :string[] = new Array("Naren","Sachin","Rahul")


Tuple
There might be a need to store a collection of values of varied types. Arrays will not serve this purpose. TypeScript gives us a data type called tuple that helps to achieve such a purpose.

Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same. For example, you may want to represent a value as a pair of a string and a number:
E.g.
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error

When accessing an element with a known index, the correct type is retrieved:
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

When accessing an element outside the set of known indices, a union type is used instead:
x[3] = "world"; // OK, 'string' can be assigned to 'string | number'

console.log(x[5].toString()); // OK, 'string' and 'number' both have 'toString'

x[6] = true; // Error, 'boolean' isn't 'string | number'


Uninon
Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type.
E.g.
let val:string|number
val = 12
console.log("numeric value of val "+val)
val = "This is a string"
console.log("string value of val "+val)
In the above example, the variable’s type is union. It means that the variable can contain either a number or a string as its value.




Enum
As in languages like C#, an enum is a way of giving more friendly names to sets of numeric values.
enum Color {Red, Green, Blue}
let c: Color = Color.Green;

By default, enums begin numbering their members starting at 0. You can change this by manually setting the value of one of its members. For example, we can start the previous example at 1 instead of 0:
enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;
Or, even manually set all the values in the enum:
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;

A handy feature of enums is that you can also go from a numeric value to the name of that value in the enum. For example, if we had the value 2 but weren’t sure what that mapped to in the Color enum above, we could look up the corresponding name:
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];
alert(colorName);


Any
The any data type is the super type of all types in TypeScript. It denotes a dynamic type. Using the any type is equivalent to opting out of type checking for a variable.
We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:
let notSure: any = 4;
notSure = "maybe a string instead"; // ok
notSure = false; // ok
The any type is also handy if you know some part of the type, but perhaps not all of it. For example, you may have an array but the array has a mix of different types:
let list: any[] = [1, true, "free"];

list[1] = 100;


Void
Used on function return types to represent non-returning functions
function warnUser(): void {
   alert("This function just alerts and returns nothing from function");
}
Declaring variables of type void is not useful because you can only assign undefined or null to them.


Null
Represents an intentional absence of an object value.


Undefined
Denotes value given to all uninitialized variables



No comments:

Post a Comment