- Defining a Variable - how to define a variable of a specific datatype
- Defining a Constant - how to define an immutable variable
- Complex Literals - native support for literal complex datatypes (non-primitive types)
Variables and Constants
Change TopicSelect Language
TypeScript Variables
Variables
let x: number = 100;
Constants
const PI: number = 3.1415; // Immutable constant
Literals
The following primitive literals are covered by Typescript:
let myInt: number = 10; let myBinary: number = 0b1010; let myOctal: number = 0o12; let myHex: number = 0xa; let myFloat: number = 10.5; let mySciNot: number = 2.0e3; let myBool: boolean = true; let myNull: null = null; let myUndefined: undefined = undefined;
String literals:
let myStr: string = "hello"; let myStrDouble: string = "hello"; let myMultiLine: string = `hello there`; // Template literals allow multi-line strings let myRaw: string = String.raw`New\nLine`; // Ignores escape sequences let myFormatted: string = `Hello ${name}`; // String interpolation
Complex literals
let myArray: number[] = [1, 2, 3]; // Standard array let myTuple: [number, number, number] = [1, 2, 3]; // Fixed-size tuple let mySingleTuple: [number] = [42]; // Tuple with one element let myObject: { key: string; age: number } = { key: "value", age: 30 }; // Object type let mySet: Set<number> = new Set([1, 2, 3]); // Set type let myEmptySet: Set<number> = new Set(); // Empty set let myBuffer: ArrayBuffer = new ArrayBuffer(8); // Equivalent to `bytes` let myTypedArray: Uint8Array = new Uint8Array([104, 101, 108, 108, 111]); // Equivalent to `bytearray`