TypeScript Basic Types

Basic types allow developers to describe the structure and intent of data more accurately.

The data types included in TypeScript are as follows:

TypeDescriptionExample
stringRepresents text datalet name: string = "Alice";
numberRepresents numbers, including integers and floating-point numberslet age: number = 30;
booleanRepresents a boolean valuetrueorfalselet isDone: boolean = true;
arrayRepresents an array of elements of the same typelet list: number[] = [1, 2, 3];
tupleRepresents an array with known types and lengthlet person: [string, number] = ["Alice", 30];
enumDefines a set of named constantsenum Color { Red, Green, Blue };
anyAny type, without type checkinglet value: any = 42;
voidNo return value (often used for functions)function log(): void {}
nullRepresents an empty valuelet empty: null = null;
undefinedRepresents undefinedlet undef: undefined = undefined;
neverRepresents no return valuefunction error(): never { throw new Error("error"); }
objectRepresents non-primitive typeslet obj: object = { name: "Alice" };
unionUnion type, meaning it can be one of multiple types`let id: string
unknownUncertain type, needs type checking before uselet value: unknown = "Hello";

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

1. string

Represents text data; can only store strings, usually used to describe textual information.

let message: string = "Hello, TypeScript!";

Template strings:TypeScript supportstemplate strings, which use backticks`(remember, not single quotes ') to define them, allowing variables or expressions to be inserted into strings. They are ideal for multi-line text and variable concatenation.

let name: string = "Alice";
let greeting: string = `Hello, ${name}! Welcome to TypeScript.`;
console.log(greeting); // 输出:Hello, Alice! Welcome to TypeScript.

2. number

TypeScript uses the number type to represent all numbers, including integers and floating-point numbers.

let age: number = 25;
let temperature: number = 36.5;

3. boolean

Represents logical values true or false, used for conditional judgments.

let isCompleted: boolean = false;

4. array

It can represent a group of elements of the same type. It can be expressed in two ways: type[] or Array<type>.

let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"];

5. tuple

Represents an array with a known count and types of elements. Each element can be a different type, suitable for representing data with a fixed structure.

let person: [string, number] = ["Alice", 25];

6. enum

Used to define a set of named constants. By default, enum values start from 0 and increase.

enum Color {
  Red,
  Green,
  Blue,
}
let favoriteColor: Color = Color.Green;

7. any

It can represent any type. It is suitable for cases where the data type is uncertain, but should be used with caution, because any bypasses type checking.

let randomValue: any = 42;
randomValue = "hello";

The any type is a data type used by TypeScript for variables whose type is 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 skip type checking during the compilation phase. Example code is as follows:

let x: any = 1;    // 数字类型
x = 'I am who I am';    // 字符串类型
x = false;    // 布尔类型

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

let x: any = 4;
x.ifItExists();    // 正确,ifItExists方法在运行时可能存在,但这里并不会检查
x.toFixed();    // 正确

When defining an array that stores data of various types, example code is as follows:

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

8. void

Used for functions without a return value. When declaring a variable, the void type means it can only be assigned null or undefined.

function logMessage(message: string): void {
  console.log(message);
}

9. null and undefined

null and undefined respectively represent "empty value" and "undefined". By default, they are subtypes of all types, but strict checking can be enabled by setting strictNullChecks.

let empty: null = null;
let notAssigned: undefined = undefined;

null

In JavaScript, null means "nothing".

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

Using typeof to detect null returns "object".

undefined

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

Calling typeof on a variable without a value returns undefined.

null and undefined are subtypes of all other types (including void), and can be assigned to other types, such as number. In this case, the type after assignment becomes null or undefined. However, when the strict null checking feature (--strictNullChecks) is enabled in TypeScript, null and undefined can only be assigned to void or their own corresponding types. Example code is as follows:

// 启用 --strictNullChecks
let x: number;
x = 1; // 编译正确
x = undefined;    // 编译错误
x = null;    // 编译错误

In the example above, 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 is as follows:

// 启用 --strictNullChecks
let x: number | null | undefined;
x = 1; // 编译正确
x = undefined;    // 编译正确
x = null;    // 编译正确

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

10. never

Represents no return value; usually used for functions that throw errors or enter infinite loops, meaning the function never terminates normally.

function throwError(message: string): never {
  throw new Error(message);
}

never is a subtype of all other types (including null and undefined), representing values that never occur. This means that a variable declared as the never type can only be assigned a value of the never type. In functions, it usually manifests as throwing an exception or failing to reach a termination point (e.g., an infinite loop). Example code is as follows:

let x: never;
let y: number;

// 编译错误,数字类型不能转为 never 类型
x = 123;

// 运行正确,never 类型可以赋值给 never类型
x = (()=>{ throw new Error('exception')})();

// 运行正确,never 类型可以赋值给 数字类型
y = (()=>{ throw new Error('exception')})();

// 返回值为 never 的函数可以是抛出异常的情况
function error(message: string): never {
    throw new Error(message);
}

// 返回值为 never 的函数可以是无法被执行到的终止点的情况
function loop(): never {
    while (true) {}
}

11. object

Represents non-primitive values, suitable for complex object structures.

let person: object = { name: "Alice", age: 30 };

12. Union types

Represents that a variable can be one of multiple types. Implemented using the | symbol.

let id: string | number;
id = "123";
id = 456;

13. unknown (uncertain type)

Similar to any, but stricter. It must be type-checked before it can be assigned to variables of other types.

let value: unknown = "Hello";
if (typeof value === "string") {
  let message: string = value;
}

14. Type Assertions

Type assertions allow developers to explicitly tell the compiler the type of a variable, often used when the type cannot be inferred. The as syntax or angle-bracket syntax can be used.

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

15. Literal types

Literal types allow a variable to have only specific values, and are used together with union types to define specific states of a variable.

let direction: "up" | "down" | "left" | "right";
direction = "up";

Through these types, TypeScript provides stronger type safety and code checking capabilities, enabling developers to express data and intent more clearly and accurately, reducing runtime errors.


Example

The following example demonstrates the definition and usage of the main basic types in TypeScript, simulating a user object and related operation functions.

Example

// Define an enum type to represent the user's role
enum Role {
  Admin,
  User,
  Guest,
}

// Use interface to define the user's structure
interface User {
  id: number;               // number type, used to uniquely identify the user
  username: string;         // string type, representing the username
  isActive: boolean;        // boolean type, indicating whether the user is active
  role: Role;               // enum type, used to represent the user role
  hobbies: string[];        // array type, storing the user's hobbies
  contactInfo: [string, number]; // tuple type, a tuple containing a phone number, in the format: [area code, phone number]
}

// Create a user object that conforms to the User interface structure
const user: User = {
  id: 1,
  username: "Alice",
  isActive: true,
  role: Role.User,
  hobbies: ["Reading", "Gaming"],
  contactInfo: ["+1", 123456789],
};

// Define a function that returns a string to get user information
function getUserInfo(user: User): string {
  return `User ${user.username} is ${user.isActive ? "active" : "inactive"} with role ${Role[user.role]}`;
}

// Use the void type to define a function that specifically prints user information
function printUserInfo(user: User): void {
  console.log(getUserInfo(user));
}

// Define a function parameter of union type, accepting a user ID (number) or username (string)
function findUser(query: number | string): User | undefined {
  // Use typeof to determine the type of query
  if (typeof query === "number") {
    // If it is a number, find the user by ID
    return query === user.id ? user : undefined;
  } else if (typeof query === "string") {
    // If it is a string, find the user by username
    return query === user.username ? user : undefined;
  }
  return undefined;
}

// Define a never-typed function to handle abnormal situations in the program
function throwError(message: string): never {
  throw new Error(message);
}

// Use the any type to handle data of unknown type
let unknownData: any = "This is a string";
unknownData = 42; // Reassign to a number, the type is any

// Use the unknown type to handle uncertain data, which is safer
let someData: unknown = "Possible data";
if (typeof someData === "string") {
  console.log(`Length of data: ${(someData as string).length}`);
}

// Call each function and test
printUserInfo(user);                    // Print user information
console.log(findUser(1));               // Find user by ID
console.log(findUser("Alice"));         // Find user by username

// Variables using null and undefined types
let emptyValue: null = null;
let uninitializedValue: undefined = undefined;

Explanation:

  • Enum type (Role): Used to define named constants for user rolesAdmin、UserandGuest。
  • Interface (User): definesUserthe structure of an object, includingid、username、isActiveproperties such as..., demonstratingstring、number、boolean、arrayandtuplethe use of types.
  • FunctiongetUserInfo: returns a description of the user, using string interpolation along withenum。
  • functionprintUserInfo: the type isvoid, because it only outputs information and does not return any value.
  • Union type (number | string): used forfindUserthe function's parameter, which can accept numbers or strings.
  • nevertype:throwErrorThe function throws an error and does not return normally, so it usesnevertype.
  • anytype: demonstrates how to declare a variable that can accept any type.
  • unknowntype: similar toany, but safer; in the example, type checking is performed before type assertion.
  • nullandundefined: demonstrates the use of null values.
Other extensions