TypeScript: TypeScript Basic Types
Last updated: 2026-08-26
TypeScript’s type system starts with seven basic types—master these, and you’ll have mastered the “alphabet” of type annotations.
1. Seven Basic Types
TypeScript inherits the seven basic types from JavaScript and provides type annotation syntax for each type:
| Type | Description | Example Value |
|---|---|---|
string |
string | "hello", 'world', `template` |
number |
Numbers (integers and decimals) | 42, 3.14, 0xFF |
boolean |
Boolean value | true, false |
null |
empty value | null |
undefined |
Undefined | undefined |
symbol |
Unique Identifier | Symbol("id") |
bigint |
large integer | 100n, BigInt(9007199254740991) |
(1) string
Strings can be denoted using single quotes, double quotes, or backticks (template strings):
let firstName: string = "Charlie";
let lastName: string = 'Wang';
let greeting: string = `Hello, ${firstName} ${lastName}`;
Template strings (backticks) support embedded variables and expressions; this syntax was introduced in ES6 and is fully supported by TypeScript.
(2) number
Like JavaScript, TypeScript does not distinguish between integers and floating-point numbers—they are both of type number:
let age: number = 25; // Integer
let price: number = 9.99; // Decimals
let hex: number = 0xFF; // Hexadecimal
let binary: number = 0b1010; // Binary
let octal: number = 0o744; // Octal
Number.MAX_SAFE_INTEGER (2^53 - 1), you should use bigint instead of number; otherwise, you will lose precision.
(3) boolean
There are only two values: true and false. They are commonly used for conditional checks and as toggle flags:
let isActive: boolean = true;
let hasPermission: boolean = false;
▶ Example: Primitive Type Annotations
// Defining Different Types of Variables
let title: string = "TypeScript Getting Started";
let version: number = 5.3;
let isPublished: boolean = true;
console.log("Courses:" + title);
console.log("Version:" + version);
console.log("Published:" + isPublished);
Output:
Courses:TypeScript Getting Started
Version:5.3
Published:true
2. null and undefined
In TypeScript, null and undefined are both values and types. The difference between them may seem subtle, but it is important in the type system.
(1) Differences in Meaning
| Type | Meaning | When it appears |
|---|---|---|
undefined |
"Not yet assigned" | Variable declared but not initialized; function has no return value |
null |
"Intentionally left blank" | Set by the developer to indicate "no value here" |
(2) Type Annotations
let notAssigned: undefined = undefined;
let emptyValue: null = null;
null and undefined can be assigned to variables of any type (for example, let name: string = null is valid). However, once strictNullChecks is enabled, they can only be assigned to types of the null/undefined type or union types. It is strongly recommended that you enable strict null checking.
(3) The Impact of strictNullChecks
// strictNullChecks: false(Default Relaxed Mode)
let name: string = null; // ✅ No errors,But at runtime name.toUpperCase() It will crash
// strictNullChecks: true(Strict Mode,Recommendations)
let name2: string = null; // ❌ Error:You cannot null Assign to string
let name3: string | null = null; // ✅ Correct:An explicit declaration might be null
strict: true includes strictNullChecks: true. In strict mode, any value that could be null or undefined must be explicitly declared; this prevents 90% of "undefined is not a function" runtime errors.
3. The symbol type
symbol is a primitive type introduced in ES6 that is used to create globally unique identifiers. Each call to Symbol() generates a unique value:
let id1: symbol = Symbol("id");
let id2: symbol = Symbol("id");
console.log(id1 === id2); // false —— Even if the descriptions are the same,Each symbol They are all unique.
▶ Example: Using a symbol as a unique key for an object
let uniqueKey: symbol = Symbol("secret");
let user = {
name: "Diana",
age: 20
};
// Use symbol as a property key,Does not conflict with other attributes
user[uniqueKey] = "Hide Data";
console.log(user.name); // Normal Access
console.log(user[uniqueKey]); // Visit symbol Key value
Output:
Diana
Hide Data
Symbol.iterator and internal framework implementations). For beginners, it's enough to understand that "Symbol() generates a unique value each time it's called."
4. The bigint Type
bigint is a type introduced in ES2020 that represents large integers beyond the safe range of number. A number followed by n is a bigint:
let big1: bigint = 100n; // Literal Notation
let big2: bigint = BigInt(9007199254740991); // Function Syntax
// number Upper Limit for Secure Integers
let maxSafe: number = Number.MAX_SAFE_INTEGER; // 9007199254740991
let overflow: number = 9007199254740992; // Outside the safety range,Loss of Accuracy!
// bigint No loss of precision
let safe: bigint = 9007199254740992n; // Precise representation
bigint and number cannot be used together in calculations—100n + 50 will result in an error. You must first standardize the type to either Number(100n) + 50 or 100n + BigInt(50).
▶ Example: Comparing bigint Precision
// number Accuracy is lost when the safe range is exceeded
let a: number = 9007199254740992;
let b: number = 9007199254740993;
console.log(a === b); // true!Two different numbers are actually equal
// bigint Precise representation
let c: bigint = 9007199254740992n;
let d: bigint = 9007199254740993n;
console.log(c === d); // false —— Distinguish Correctly
Output:
true
false
5. Omitting Type Annotations and Best Practices
(1) When is it necessary to include a type annotation?
| Scenario | Is it required? | Reason |
|---|---|---|
| Variables without initial values | ✅ Required | Otherwise, TypeScript cannot infer the type |
| Function Parameter | ✅ Required | The parameter has no initial value for inference |
| Function Return Value | ⚠️ Recommended | TypeScript can infer this, but explicit annotation provides greater clarity |
| Variable has an initial value | ❌ Optional | TypeScript infers based on the initial value |
(2) Best Practices
// ✅ Recommendations:Omit the type annotation when a variable has an initial value(Type inference is sufficient)
let name = "Charlie";
let age = 20;
// ✅ Recommendations:Explicitly Labeling Function Parameters and Return Values
function greet(name: string): string {
return "Hello, " + name;
}
// ✅ Recommendations:Explicitly label when there is no initial value
let userId: number;
let isActive: boolean;
// ❌ Not recommended:Why include annotations when there are initial values?(Redundancy)
let name2: string = "Charlie"; // Superfluous——TypeScript It has already been deduced.
❓ FAQ
null and undefined? When should each be used?undefined indicates "not yet assigned" (a state automatically generated by the system), while null indicates "intentionally empty" (a value explicitly set by the developer). In actual development, it is recommended to use null to indicate "no value"—because undefined may result from forgetting to assign a value, whereas null represents a deliberate choice.bigint type commonly used?number type is sufficient (with a safe integer range up to 2^53-1 ≈ 900 trillion). bigint is primarily used in scenarios such as cryptographic algorithms, large-number computations, and bigint fields in databases. Beginners just need to be aware that it exists; they can delve deeper when they actually need to use it.📖 Summary
- TypeScript has seven basic types: string, number, boolean, null, undefined, symbol, and bigint
- The
numbertype does not distinguish between integers and decimals;bigintis used for very large integers and cannot be used in mixed operations withnumber. - In strict mode,
nullorundefinedcannot be arbitrarily assigned to other types; you must use a union type (string | null). - symbol: Generates a globally unique identifier, primarily used in advanced scenarios
- Type annotations can be omitted when variables have initial values (type inference); function parameters and variables without initial values must be annotated.
📝 Exercises
- Basic Problem (Difficulty ⭐): Declare five variables corresponding to five common types (string, number, boolean, null, undefined), assign appropriate values to them, and use
console.logto print them one by one. - Advanced Problem (Difficulty ⭐⭐): Write a function
formatPrice(price: number, currency: string): stringthat formats a numeric price into a string with a currency symbol. For example,formatPrice(99.5, "¥")returns"¥99.5". - Challenge Problem (Difficulty ⭐⭐⭐): Verify the precision of
number—write code to compare whether0.1 + 0.2and0.3are equal, and explain the result. Then, usebigintto calculate the sum of two large integers that exceedNumber.MAX_SAFE_INTEGER, and verify thatbigintdoes not lose precision.