TypeScript Cheatsheet
TypeScript
Install globally
npm install -g typescript
Within your npm project, run the following command to install the compiler:
npm install typescript --save-dev
The compiler is installed in the node_modules directory and can be run with:
npx tsc
Check Version
tsc --version
The compiler can be configured using a tsconfig.json file.
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
{
"include": ["src"],
"compilerOptions": {
"outDir": "./build"
}
}
This behavior can be disabled by enabling noImplicitAny as an option in a TypeScript's project
tsconfig.json.Primitives in TypeScript
boolean - true or false values
number - whole numbers and floating point values
string - text values like "TypeScript Rocks"
bigint - allows larger numbers
symbol - used to create a globally unique identifier
Explicit Type - writing out the type:
let firstName: string = "Dylan";Implicit Type - TypeScript will "guess" the type, based on the assigned value:
let firstName = "Dylan";Type: any
Setting any to the special type any disables type checking:
let v: any = true;v = "string"; // no errorMath.round(v); // no errorType: unknown
unknown is best used when you don't know the type of data being typed. To add a type later, you'll need to cast it.
let w: unknown = 1;w = "string"; // no errorCasting is when we use the "as" keyword to say property or variable is of the casted type.
Type: never
never effectively throws an error whenever it is defined.
let x: never = true;Type: undefined & null
let y: undefined = undefined;let z: null = null;Arrays
const names: string[] = [];names.push("Dylan"); // no error// names.push(3); // Error
Readonly
The readonly keyword can prevent arrays from being changed.
const names: readonly string[] = ["Dylan"];// names.push("Jack"); // Error
Type Inference
TypeScript can infer the type of an array if it has values.
const numbers = [1, 2, 3]; // inferred to type number[]numbers.push(4); // no error// numbers.push("2"); // Error
let head: number = numbers[0]; // no errorTyped Arrays (Tuples)
A tuple is a typed array with a pre-defined length and types for each index.
let ourTuple: [number, boolean, string];ourTuple = [5, false, 'Coding God was here'];Readonly Tuple Example
const ourReadonlyTuple: readonly [number, boolean, string] = [5, true, 'The Real Coding God'];// ourReadonlyTuple.push('Coding God took a day off'); // Error