Easy Tutorial
❮ Ts Basic Syntax Ts String ❯

TypeScript Basic Types

TypeScript includes the following data types as shown in the table below:

Data Type Keyword Description
Any Type any Variables declared as any can be assigned values of any type.
Number Type number A double-precision 64-bit floating-point value. It can be used to represent both integers and fractions. let binaryLiteral: number = 0b1010; // Binary<br>let octalLiteral: number = 0o744; // Octal<br>let decLiteral: number = 6; // Decimal<br>let hexLiteral: number = 0xf00d; // Hexadecimal
String Type string A sequence of characters, using single quotes (') or double quotes (") to represent string types. Backticks () are used to define multi-line text and embedded expressions. let name: string = "tutorialpro";<br>let years: number = 5;<br>let words: string =Hello, this year marks ${ name }'s ${ years + 1}th anniversary`;
Boolean Type boolean Represents logical values: true and false. let flag: boolean = true;
Array Type N/A Declares variables as arrays. // Adding [] after the element type<br>let arr: number[] = [1, 2];<br>// Or using array generics<br>let arr: Array<number> = [1, 2];
Tuple N/A Tuple types are used to represent arrays with known elements and types, where the types do not need to be the same, but the types at corresponding positions must match. let x: [string, number];<br>x = ['tutorialpro', 1]; // Runs correctly<br>x = [1, 'tutorialpro']; // Throws an error<br>console.log(x[0]); // Outputs tutorialpro
Enum enum Enum types are used to define collections of values. enum Color {Red, Green, Blue};<br>let c: Color = Color.Blue;<br>console.log(c); // Outputs 2
Void void Used to denote the return type of a method, indicating that the method does not return a value. function hello(): void {<br> alert("Hello tutorialpro");<br>}
Null null Indicates a missing object value.
Undefined undefined Used to initialize a variable to an undefined value.
Never never never is a subtype of other types (including null and undefined), representing values that never occur.

Note: TypeScript and JavaScript do not have an integer type.


Any Type

Any value is a data type in TypeScript used for variables whose types are unclear during programming. It is commonly used in the following three situations.

  1. When the value of a variable changes dynamically, such as input from the user, the any type allows these variables to bypass type checking during the compilation phase. Example code:
    let x: any = 1;    // Number type
    x = 'I am who I am';    // String type
    x = false;    // Boolean type
    

When rewriting existing code, any allows type checking to be selectively included or removed during compilation. Example code:

let x: any = 4;
x.ifItExists();    // Correct, ifItExists method may exist at runtime, but it will not be checked here
x.toFixed();    // Correct

When defining an array to store data of various types, example code:

let arrayList: any[] = [1, false, 'fine'];
arrayList[1] = 100;

Null and Undefined

null

In JavaScript, null represents "nothing".

null is a special type with only one value. It represents an empty object reference.

Using typeof to check for null returns "object".

undefined

In JavaScript, undefined is a variable that has not been assigned a value.

typeof a variable without a value returns "undefined".

Null and Undefined are subtypes of other types (including void) and can be assigned to other types, such as number types. However, with TypeScript's strict null checks (--strictNullChecks) enabled, null and undefined can only be assigned to void or their own types. Example code:

// Enable --strictNullChecks
let x: number;
x = 1; // Compiles correctly
x = undefined;    // Compilation error
x = null;    // Compilation error

In the above example, variable x can only be of number type. If a type may be null or undefined, you can use | to support multiple types. Example code:

// Enable --strictNullChecks
let x: number | null | undefined;
x = 1; // Compiles correctly
x = undefined;    // Compiles correctly
x = null;    // Compiles correctly

For more information, see: JavaScript typeof, null, and undefined


never Type

never is a subtype of other types (including null and undefined), representing values that never occur. This means that variables declared as never can only be assigned values of never type. In functions, it typically manifests as throwing exceptions or failing to reach a termination point (such as an infinite loop). Example code:

let x: never;
let y: number;

// Compilation error, number type cannot be converted to never type
x = 123;

// Runs correctly, never type can be assigned to never type
x = (()=>{ throw new Error('exception')})();

// Runs correctly, never type can be assigned to number type
y = (()=>{ throw new Error('exception')})();

// Functions returning never can throw an exception
function error(message: string): never {
    throw new Error(message);
}

// Functions returning never can fail to reach a termination point
function loop(): never {
    while (true) {}
}

Reference article: https://segmentfault.com/a/1190000008893626

❮ Ts Basic Syntax Ts String ❯