javascript has
number, string, boolean, null, undefined, object
typescript inherits aboe and has extra:
any, unknown, never, enum, tuple
compiler can drive data type, so below two are the same
let a:number = 1;
let a = 1;
if not declared, data type is set to any by default. It just means compile doesnt enforce type check.
Note that this should be avoided as much as possible, because type check is the point of using typescript.
let b;
b =1;
b ='a';
Array and forEach
let nums: number[] = [1,2,3]
This iterate through each item and do someting, NOTE this does not overwrite old array, just do sth in the loop.
let nums2 = nums.forEach(n => n * 2)
To return an array to overwrite existing array, use map, which combines the result returned in the arrow (anonymous) function.
let nums3 = nums.map(n => {return n * 2})
Tuple
Tuple is a concept in typescript but actually just implemented as a two element array in javascript
let b: [number, string] = [1,'abc']
Enum
enum Sth {A=1, B=2}
let ss: Sth = Sth.B
Data types
The use of semicolons in JavaScript is optional, will be added incompilation
The let and const fix a lot of the problems with var in original Java script
The "Let" declares a variable with type, e.g. number, bollean, string, array, tuple, enum
let a: number = 18;
const b: boolean = true; //can be constant
let c: string = 'good';
let d: [string, number] = ['good', 1]; //tuple
let e: Array<string> = ['good'];
enum Color {Red = 1,Green = 2,}; //enumeration type
let f: Color = Color.Green;
let g: unknown = 4; //unknown type, so it can change later
g = 'good';
function getValue(key: string):any{ //use any to opt out type checking
return 'abc' + key
};
let str: string = getValue('hey');
function printxy(): void { //use void to return nothing
console.log("xy");
};
Difference between unknown and any is that:
unknown is the parent type of all other types, while any means "disable type check during compilation", its a compiler directive.
null and undefined types can be assigned to other types
Difference between null and undefined is that:
undefined means the variable has been declared, but the value has not been assigned yet.
null means empty or blank value, i.e. intentional absence of a value
never type is for the values that never occur
// Function throws an error before return
function error(message: string): never {
throw new Error(message);
};
//function never returns
function infiniteLoop(): never {
while (true) {}
};
object is a type that represents the non-primitive type, i.e. anything that is not number, string, boolean, bigint, symbol, null, or undefined