Typescript: Getting Started - SPFx Development (Part 5)
We saw how to use variable declarations in the Part 4 of this series. Now lets see how to work with project files and compiler options.
Basic Types
So as to work with the various data types just as in Javsascript, Typescript also has the similar datatypes which are :
- Boolean
- Number
- String
- Array
- Tuple
- Enum
- Any
- Void
- Null and Undefined
- Never
- Object
Boolean :
It’s the most basic data type which either accepts True/False value and the declaration goes like :
let flag: boolean = true;
Type Annotation and Type Inference
In the above section we have used annotations to describe what kind of datatype the flag variable holds. Annotations are specified by placing the semi column just after the variable name followed by the data type.
let flag: boolean = true;
Here the flag is annotated with the Boolean data type and value true is assigned to it.
However Typescript compiler is intelligent enough to understand and infer the datatype even if we do not use Type Annotation.
Let flag = true will be inferred by the compiler that flag is of type Boolean and value is true. If we try to assign a string or number to flag again, it will throw a compile time error.
Number
As in JavaScript, all numbers in TypeScript are floating point values. In addition to hexadecimal and decimal literals, TypeScript also supports binary and octal literals.
Variables can be declared as :
- let decimal: number = 123456789;
- let hex: number = 75BCD15;
- let binary: number = 0b1010;
- let octal: number = 0o744;
String
String data type accepts textual data. As in Javascript, we can use Double Quotes or Single Quotes to surround the text data. The declaration syntax goes like :
let message: string = "Hello World !";
Template Strings
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 AuthorName = "Priyaranjan KS"
- console.log(`The Author's name is ${ AuthorName }`);
Running this in the TypescriptLang Playground would look like below :
Array
Just like any other language, TS allows us to use the datatype Array to work with a collection of values. We can define array in two ways :
In the first, we use the type of the elements followed by [] to denote an array of that element type:
let collection: number[] = [1, 2, 3];
The second way uses a generic array type, Array<elemType>:
let list: Array<number> = [1, 2, 3];
Tuple
Tuple types allow one to express an array with a fixed number of elements whose types are known, but need not be the same. For example, we may want to represent a value as a pair of a string and a number which we can do as below:
- let tupleCollection: [string, number] = ["HelloWorld", 500]
- console.log("Full Tuple : "+tupleCollection);
- console.log("First Element : "+tupleCollection[0]);
Enum
An additional datatype to the standard set of datatypes from JavaScript is the enum. As in languages like C#, an enum is a way of giving more friendly names to sets of numeric values.
- enum Month {January, February, March,April}
- let M: Month = Month. March;
- console.log("The Month Value is : "+M)
Here the Month enum has month names collection which by default starts value from 0. Hence January will have the value 0 and subsequent elements will have the incremented value. However, if we want the value to start from a different integer, we can specify that as well.
Or if we want to specify the value for each element, that is also possible.
Any
We may have to define the type of variables that we do not know when we are writing an application. The values for these variables may be assigned dynamically during run time as a result of some code execution or it may be coming from a third party library. We can use any datatype as :
- let Something: any = "HelloWorld!";
- console.log("Value of Something is : " + Something);
- Something = 100;
- console.log("Value of Something is : " + Something);
- Something = true;
- console.log("Value of Something is : " + Something);
Thus we can assign any values to the variable if it is defined with any datatype and during execution we can assign any values without generating a compile error.
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 Collection: any[] = [“January”, 100, false];
Void
Void data type is used to indicate the absence of having any type at all. We usually use this as the return type of functions that do not return a value:
- function ShowMessage(): void {
- alert("Hello World !");
- }
Assigning void to a variable is not programatically useful as you can only assign null or undefined to them.
Null and Undefined
Typescript also provides us with 2 other types Null and Undefined which can be assigned to variables to show that they hold any values.
- let UndefinedVar: undefined = undefined;
- let NullVar: null = null;
when using the --strictNullChecks flag, null and undefined are only assignable to any type and Undefined/Null Types.Else we can even assign them with other datatypes like string. However as a best coding practise, its adviced to use –strictNullChecks.
–strictNullChecks
By default null and undefined are assignable to other data type variables if strict null check is not enabled. Hwever once we have enabled this compiler option, we can the null and undefined values to only those variables that are declares with any type or the null/undefined type.
Assigning null/undefined to any other types will cause compile time errors. We can enable strictNullCheck by changing the property value in the tsconfig.json.
Once it is turned to true, the below code compilation will happen accordingly :
- let a : number =10
- a = null //Compilation error
- let b : null = null //Compiles OK
Never
The never data type is used to represent values that will never occur.
Union Types
There can be a situation where we would expect either a string or a number to be saved to a variable. In such situation TypeScript allows us to use more than one data type for a variable or a function parameter. Let see how to use union types with
Variable as Union Type :
- let EmployeeID: string | number;
- EmployeeID = 1;
- EmployeeID = "Emp1";
- EmployeeID = False; // Compiler Error
Here the variable EmployeeID can accept either a number value or a string value as we have declared it using Union Type string | number. The vertical bar indicates the union of the possible data types . However any other data type value assigned to it will generate compile time error .
Function Parameter as Union Type :
The function parameter can also be of union type,as shown below :
- function AssignEmployeeID(ID: (string | number))
- {
- if(typeof(ID) === "number")
- console.log('Employee ID is number.')
- else if(typeof(ID) === "string")
- console.log('Employee ID is string.')
- }
- AssignEmployeeID(123);
- AssignEmployeeID("ABC");
Here we can see that the ID parameter in the function is assigned a union type so that it can accept either a string or number as the input parameter to the function. Any other data type being passed will generate a compile time error.