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):

TYPESCRIPT
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:

TYPESCRIPT
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
💡 Tip: If your calculations involve very large integers exceeding 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:

TYPESCRIPT
let isActive: boolean = true;
let hasPermission: boolean = false;

▶ Example: Primitive Type Annotations

TYPESCRIPT
// 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);
▶ Try it Yourself

Output:

TEXT 📖 Display only
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

TYPESCRIPT
let notAssigned: undefined = undefined;
let emptyValue: null = null;
⚠️ Note: By default, 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

TYPESCRIPT
// 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
📌 Key Point: 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:

TYPESCRIPT
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

TYPESCRIPT
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
▶ Try it Yourself

Output:

TEXT 📖 Display only
Diana
Hide Data
💡 Tip: Symbols aren't used very often in everyday development; they mainly appear in advanced scenarios (such as the iterator protocol 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:

TYPESCRIPT
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
🔥 Common Mistake: 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

TYPESCRIPT
// 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
▶ Try it Yourself

Output:

TEXT 📖 Display only
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

TYPESCRIPT
// ✅ 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

Q Does TypeScript have float or double types?
A No. Just like JavaScript, TypeScript has only one number type, which covers both integers and floating-point numbers. JavaScript numbers are all 64-bit double-precision floating-point numbers (IEEE 754), so 1 and 1.0 are exactly the same in terms of type.
Q What is the practical difference between null and undefined? When should each be used?
A 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.
Q Is the bigint type commonly used?
A Not really. In the vast majority of cases, the 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.
Q Does using too many type annotations affect performance?
A Not at all. Type annotations exist only at compile time; all type information is removed from the compiled JavaScript code, so there is zero runtime overhead. Just as comments don’t slow down a program.

📖 Summary

📝 Exercises

  1. Basic Problem (Difficulty ⭐): Declare five variables corresponding to five common types (string, number, boolean, null, undefined), assign appropriate values to them, and use console.log to print them one by one.
  2. Advanced Problem (Difficulty ⭐⭐): Write a function formatPrice(price: number, currency: string): string that formats a numeric price into a string with a currency symbol. For example, formatPrice(99.5, "¥") returns "¥99.5".
  3. Challenge Problem (Difficulty ⭐⭐⭐): Verify the precision of number—write code to compare whether 0.1 + 0.2 and 0.3 are equal, and explain the result. Then, use bigint to calculate the sum of two large integers that exceed Number.MAX_SAFE_INTEGER, and verify that bigint does not lose precision.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏