Basic types allow developers to more accurately describe the structure and intent of data.
TypeScript includes the data types listed in the following table:
| Type | Description | Example |
|---|---|---|
string |
Represents textual data | let name: string = "Alice"; |
number |
Represents numbers, including integers and floating-point numbers | let age: number = 30; |
boolean |
Represents a boolean value true or false |
let isDone: boolean = true; |
array |
Represents an array of elements of the same type | let list: number[] = [1, 2, 3]; |
tuple |
Represents an array with known types and length | let person: [string, number] = ["Alice", 30]; |
enum |
Defines a set of named constants | enum Color { Red, Green, Blue }; |
any |
Any type, no type checking is performed | let value: any = 42; |
void |
No return value (commonly used for functions) | function log(): void {} |
null |
Represents an empty value | let empty: null = null; |
undefined |
Represents undefined | let undef: undefined = undefined; |
never |
Represents a value that will never be returned | function error(): never { throw new Error("error"); } |
object |
Represents non-primitive types | let obj: object = { name: "Alice" }; |
union |
Union type, represents a value that can be one of several types | let id: string | number; |
unknown |
Unknown type, requires type checking before use | let value: unknown = "Hello"; |
Note: TypeScript and JavaScript do not have an integer type.
1. string
Represents textual data, can only store strings, and is typically used to describe textual information.
let message: string = "Hello, TypeScript!";
Template Strings: TypeScript supports template strings, defined using backticks ` (remember, not single quotes '). They allow inserting variables or expressions within the string, making them very suitable for multi-line text and variable concatenation.
let name: string = "Alice";
let greeting: string = `Hello, ${name}! Welcome to TypeScript.`;
console.log(greeting); // Output: Hello, Alice! Welcome to TypeScript.
2. number
TypeScript uses number to represent all numbers, including integers and floating-point numbers.
let age: number = 25;
let temperature: number = 36.5;
3. boolean
Represents the logical values true or false, used for conditional checks.
let isCompleted: boolean = false;
4. array
Represents a collection of elements of the same type. Can be represented using type[] or Array<type>.
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"];
5. tuple
Represents an array with a known number and types of elements. Each element can be of 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, the values of an enum start from 0 and increment.
enum Color { Red, Green, Blue }
let favoriteColor: Color = Color.Green;
7. any
Can represent any type. Suitable for situations where the data type is uncertain, but use it with caution because any bypasses type checking.
let randomValue: any = 42;
randomValue = "hello";
any is a data type used in TypeScript for variables with unclear types during programming. It is commonly used in the following three scenarios:
1. When the value of a variable will change dynamically, such as user input. The any type allows these variables to skip type checking during compilation. 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 optionally including or removing type checking at compile time. Example code:
let x: any = 4;
x.ifItExists(); // Correct, ifItExists method may exist at runtime, but it won't be checked here
x.toFixed(); // Correct
When defining an array that stores various types of data. Example code:
let arrayList: any[] = [1, false, 'fine'];
arrayList = 100;
8. void
Used for functions that do not return a value. When declaring a variable, the type void means it can only be assigned null or undefined.
function logMessage(message: string): void {
console.log(message);
}
9. null and undefined
null and undefined represent "empty value" and "undefined" respectively. By default, they are subtypes of all types, but this can be controlled by setting strictNullChecks.
let empty: null = null;
let notAssigned: undefined = 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 detect 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 every other type (including void), and can be assigned to other types, such as number. In this case, the type after assignment becomes null or undefined. In TypeScript, enabling strict null checking (--strictNullChecks) ensures that null and undefined can only be assigned to void or their respective types. Example code:
// Enable --strictNullChecks
let x: number;
x = 1; // Compiles correctly
x = undefined; // Compilation error
x = null; // Compilation error
In the above example, the variable x can only be of type number. If a type might 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
10. never
Represents a value that will never be returned. Typically used for functions that throw errors or enter infinite loops, indicating that the function will never complete normally.
function throwError(message: string): never {
throw new Error(message);
}
never is a subtype of every other type (including null and undefined), representing a value that will never occur. This means a variable declared as never can only be assigned a never type. In functions, it typically manifests as throwing an exception or being unable to reach a termination point (e.g., 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') })();
// A function with a return type of never can be a situation that throws an exception
function error(message: string): never {
throw new Error(message);
}
// A function with a return type of never can be a termination point that cannot be executed
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 a variable that can be one of several types. Implemented using the | symbol.
let id: string | number;
id = "123";
id = 456;
13. unknown
Similar to any, but stricter. It must undergo type checking before being assigned to other type variables.
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, commonly used in situations where inference is not possible. Can use the as syntax or the angle-bracket syntax.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
15. Literal Types
Literal types allow a variable to only have specific values, used in conjunction with union types to define specific states for variables.
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 user roles
enum Role {
Admin,
User,
Guest,
}
// Use an interface to define the structure of a User
interface User {
id: number; // number type, for uniquely identifying the user
username: string; // string type, representing the username
isActive: boolean; // boolean type, indicating if the user is active
role: Role; // enum type, representing the user's role
hobbies: string[]; // array type, storing the user's hobbies
contactInfo: [string, number]; // tuple type, containing phone number info, 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]}`;
}
// Define a function with void type to print user information
function printUserInfo(user: User): void {
console.log(getUserInfo(user));
}
// Define a function with a union type parameter, accepting a user ID (number) or username (string)
function findUser(query: number | string): User | undefined {
// Use typeof to check the type of query
if (typeof query === "number") {
// If it's a number, find the user by ID
return query === user.id ? user : undefined;
} else if (typeof query === "string") {
// If it's a string, find the user by username
return query === user.username ? user : undefined;
}
return undefined;
}
// Define a function with never type to handle exceptional program situations
function throwError(message: string): never {
throw new Error(message);
}
// Use any type to handle data of unknown type
let unknownData: any = "This is a string";
unknownData = 42; // Reassign to a number, type is any
// Use 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 various functions and test
printUserInfo(user); // Print user information
console.log(findUser(1)); // Find user by ID
console.log(findUser("Alice")); // Find user by username
// Use variables of null and undefined types
let emptyValue: null = null;
let uninitializedValue: undefined = undefined;
Explanation:
- Enum Type (
Role): Used to define named constants for user roles:Admin,User, andGuest. - Interface (
User): Defines the structure of theUserobject, including properties likeid,username,isActive, etc., demonstrating the use ofstring,number,boolean,array, andtupletypes. - Function
getUserInfo: Returns a descriptive string of the user, using string interpolation and incorporating theenum. - Function
printUserInfo: Has typevoidbecause it only outputs information and does not return any value. - Union Type (
number | string): Used for the parameter of thefindUserfunction, which can accept a number or a string. neverType: ThethrowErrorfunction throws an error and does not return normally, hence the use of thenevertype.anyType: Demonstrates how to declare a variable that can accept any type.unknownType: Similar toany, but safer. The example performs a type check before type assertion.nullandundefined: Demonstrates the use of empty values.
YouTip