Types
Main Primitives
Section titled “Main Primitives”- Boolean
- Number
- String
Explicit
Section titled “Explicit”let firstName: string = 'Matt';
Implicit
Section titled “Implicit”let firstName = 'Matt';
In some cases, type can be inferred from the value.
Disables type checking. Unsafe.
let x = true;x = 'string'; // Error: Type 'string' is not assignable// to type 'boolean'.Math.round(x); // Error: Argument of type 'boolean' is// not assignable to parameter of type 'number'.
// Now with anylet y: any = true;y = 'string'; // no error; can be "any" typeMath.round(y); // no error; can be "any" type
Unknown
Section titled “Unknown”Kind of like any, but not as unsafe. Better to use unknown over any if you don’t know the type.
let z: unknown = 1;z = 'string'; // no errorz = { runANonExistentMethod: () => { console.log('I am running a non existent method'); },} as { runANonExistentMethod: () => void };// In the absence of type information, what measures can// we take to prevent the occurrence of the error in the// code snippet that has been commented out?// z.runANonExistentMethod(); // Error: Object is of type// 'unknown'.if (typeof z === 'object' && z !== null) { (z as { runANonExistentMethod: Function }).runANonExistentMethod();}// We cast multiple times, we can check in the if() if our// type is secure and have a safer casting.
Forces an error.
let a: never = false; // Error: Type 'boolean' is not// assignable to type 'never'.
Null & Undefined
Section titled “Null & Undefined”Primitives in JS, but also types in TS.
let b: undefined = undefined;let c: null = null;
strictNullChecks must be enabled in tsconfig.json