What Are Primitive Types in TypeScript?

Learn What Are Primitive Types in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Primitive Types in TypeScript

Primitive types represent the basic kinds of values used in a program. TypeScript supports JavaScript's primitive values and adds static type checking so developers can describe the values their variables, function parameters, and return expressions are expected to contain.

The main primitive types in TypeScript are string, number, boolean, bigint, symbol, null, and undefined. Each type represents a different kind of value and supports different operations. For example, strings represent text, numbers represent numeric values, and Booleans represent true or false conditions.

Understanding primitive types is essential before moving on to arrays, objects, interfaces, unions, generics, and more advanced TypeScript concepts. Correctly choosing primitive types helps make function contracts clear, prevents many incompatible assignments, and improves code completion in development tools.

1. The string Type

The string type represents textual data. It is commonly used for names, descriptions, messages, identifiers, URLs, and other values expressed as text.

let username: string = "Asha";
let courseName: string = "TypeScript";
let message: string = "Welcome to learning TypeScript";

console.log(username);
console.log(courseName);
console.log(message);

The colon followed by string is a type annotation. It tells TypeScript that each variable is expected to contain a string. Assigning a number or a Boolean to one of these variables produces a type error during checking.

let language: string = "TypeScript";

// Compile-time error:
// language = 100;

Strings can use single quotes, double quotes, or backticks. Backticks create template literals, which allow expressions to be embedded in a string.

const learner = "Asha";
const topic = "TypeScript";

const greeting = `Hello, ${learner}!`;
const description = `You are learning ${topic}.`;

console.log(greeting);
console.log(description);

Common string operations include toUpperCase(), toLowerCase(), trim(), includes(), and substring(). TypeScript provides editor suggestions for these methods because it knows the value is a string.

2. The number Type

The number type represents JavaScript numeric values, including integers and floating-point numbers. Unlike languages that define separate standard types for integers and decimals, TypeScript uses one number type for both.

let age: number = 25;
let price: number = 49.99;
let temperature: number = -5;
let quantity: number = 3;

console.log(age);
console.log(price);
console.log(temperature);
console.log(quantity);

Numbers support arithmetic operations such as addition, subtraction, multiplication, and division. TypeScript checks that the operands used in these operations are compatible with the required types.

function calculateTotal(
  price: number,
  quantity: number
): number {
  return price * quantity;
}

console.log(calculateTotal(100, 3));

// Compile-time error:
// calculateTotal("100", 3);

The number type can still represent special numeric results such as NaN and positive or negative Infinity. An annotation alone does not guarantee that a number is finite or appropriate for a business calculation.

When processing financial values, measurements, or values received from external sources, consider the precision requirements and add appropriate validation instead of assuming every number is valid.

3. The boolean Type

The boolean type represents the two logical values true and false. It is used for conditions, permissions, feature flags, validation results, and application states that have two possible outcomes.

let isLoggedIn: boolean = true;
let hasPermission: boolean = false;
let isPublished: boolean = true;

function canAccess(
  loggedIn: boolean,
  permitted: boolean
): boolean {
  return loggedIn && permitted;
}

console.log(isLoggedIn);
console.log(isPublished);
console.log(canAccess(isLoggedIn, hasPermission));

Boolean values are commonly used with logical operators such as AND (&&), OR (||), and NOT (!). These operators help combine conditions and control which parts of a program execute.

TypeScript distinguishes Boolean values from numbers and strings. Although JavaScript allows values such as zero and an empty string to behave as falsy values in conditions, these values are not themselves of type boolean.

Use descriptive names such as isActive, hasPermission, and shouldRetry. Good Boolean names make conditions easier to read and communicate the meaning of the check.

4. Type Inference for Primitive Values

TypeScript does not require explicit annotations for every primitive value. When a variable is initialized with a recognizable value, the compiler can often infer its type automatically.

let username = "Asha";
// Inferred type: string

let age = 25;
// Inferred type: number

let isAvailable = true;
// Inferred type: boolean

console.log(username);
console.log(age);
console.log(isAvailable);

// Compile-time error:
// age = "twenty-five";

Inference means TypeScript determines the type from the initializer instead of requiring a written annotation. The inferred type still participates in static checking, so incompatible later assignments can be reported.

Use explicit annotations when a variable is declared without an initializer, when a specific type contract needs to be communicated, or when the inferred type does not express the intended range of values.

5. Literal Types for Primitive Values

A literal type restricts a value to one specific string, number, or Boolean literal. Literal types are useful when a variable should represent a particular constant or one of a small number of allowed choices.

let courseStatus: "draft" | "published" = "draft";

courseStatus = "published";

// Compile-time error:
// courseStatus = "archived";

let retryCount: 3 = 3;

// Compile-time error:
// retryCount = 4;

console.log(courseStatus);
console.log(retryCount);

The courseStatus variable accepts only the two declared strings. The retryCount variable accepts only the numeric literal 3.

Literal types are particularly useful for request states, user roles, configuration modes, and other values with a known set of valid options. They help prevent invalid states from being represented accidentally.

A const declaration can also preserve a primitive literal type because its binding cannot be reassigned. In contrast, a let declaration initialized with a string will commonly be inferred as the broader string type so that it can receive other strings.

6. The bigint Type

The bigint type represents integers that may exceed the precision range of ordinary JavaScript numbers. It is useful for working with very large integer values when ordinary number arithmetic cannot preserve the required integer precision.

const largeNumber: bigint = 9007199254740993n;
const anotherNumber: bigint = 100n;

const result = largeNumber + anotherNumber;

console.log(largeNumber);
console.log(result);

BigInt literals use the letter n at the end of the integer literal. BigInt arithmetic supports operations such as addition, subtraction, and multiplication, but BigInt and number values cannot be mixed directly in most arithmetic expressions.

const largeValue = 100n;
const normalValue = 10;

// Compile-time error:
// const result = largeValue + normalValue;

const validResult = largeValue + BigInt(normalValue);

console.log(validResult);

BigInt support depends on the JavaScript environment and TypeScript target configuration. Configure the compiler for an appropriate JavaScript target, such as ES2020 or later, and use a runtime that supports BigInt.

Conversion between number and bigint should be deliberate. Converting a large BigInt into a number can lose precision, so keep values in the appropriate numeric type for the operations the application performs.

7. The symbol Type

The symbol type represents unique symbol values. A symbol is commonly created with the Symbol() function and can be used as an object property key when a unique key is required.

const firstId: symbol = Symbol("id");
const secondId: symbol = Symbol("id");

console.log(firstId === secondId); // false

const record = {
  [firstId]: 101
};

console.log(record[firstId]); // 101

Each call to Symbol() creates a unique symbol, even when the same description is supplied. The description is useful for debugging but does not determine symbol identity.

Symbols can be useful when creating unique object keys or integrating with JavaScript features that use well-known symbols. They are less commonly needed for ordinary application data than strings, numbers, and Booleans.

TypeScript also supports unique symbol types for particular symbol declarations. These preserve the identity of a specific symbol at the type level and are useful in specialized APIs that rely on unique keys.

8. The null Type

The null value is commonly used to represent an intentionally absent or empty value. In TypeScript, the null type allows a variable to hold null when the declared type permits it.

let selectedCourse: string | null = null;

selectedCourse = "TypeScript";

// A course can be cleared again.
selectedCourse = null;

console.log(selectedCourse);

The union type string | null indicates that selectedCourse can contain either a string or null. This makes the possibility of an absent selection explicit in the type definition.

When strict null checking is enabled, null is not automatically assignable to ordinary types such as string and number. You must explicitly include null in the type when it is a valid value.

function displayCourse(
  course: string | null
): string {
  if (course === null) {
    return "No course selected";
  }

  return course.toUpperCase();
}

console.log(displayCourse(null));
console.log(displayCourse("TypeScript"));

Checking for null narrows the union to string in the remaining branch. TypeScript can then safely allow string operations on the value.

9. The undefined Type

The undefined value commonly represents a missing value, an uninitialized optional value, or the result of accessing a property that does not exist. The undefined type makes it possible to describe these situations explicitly.

let username: string | undefined;

username = "Asha";

console.log(username);

username = undefined;

console.log(username);

The variable is allowed to contain either a string or undefined. This is useful when a value is optional or may not have been supplied yet.

Functions can also return undefined as part of an explicit union type when a result may not exist.

function findCourseName(
  id: number
): string | undefined {
  if (id === 1) {
    return "TypeScript Fundamentals";
  }

  return undefined;
}

const courseName = findCourseName(2);

if (courseName !== undefined) {
  console.log(courseName.toUpperCase());
} else {
  console.log("Course not found");
}

The function returns a string for the supported identifier and undefined when the course is not found. The caller checks the result before using a string-specific method.

10. Understanding null and undefined

Null and undefined both represent missing or absent values, but they can have different meanings in application logic. Null often indicates an intentionally empty value, while undefined commonly represents an omitted or unavailable value.

let selectedUser: string | null = null;
let searchQuery: string | undefined;

searchQuery = undefined;
selectedUser = "Asha";

console.log(selectedUser);
console.log(searchQuery);

The distinction becomes particularly important when working with optional object properties, function parameters, API responses, and configuration values.

With strict null checking enabled, include null or undefined in a declared type when the application permits those values. Then use explicit checks, optional chaining, or nullish coalescing to handle their absence appropriately.

function getDisplayName(
  name: string | null | undefined
): string {
  return name ?? "Guest";
}

console.log(getDisplayName("Asha"));
console.log(getDisplayName(null));
console.log(getDisplayName(undefined));

The nullish coalescing operator (??) returns the fallback when the value is null or undefined. Unlike the logical OR operator (||), it does not replace legitimate falsy values such as an empty string, zero, or false.

11. Primitive Types and the typeof Operator

JavaScript's typeof operator reports a string describing the runtime type category of a value. TypeScript also uses typeof checks for control-flow analysis, allowing the compiler to narrow union types within conditional branches.

function displayValue(
  value: string | number | boolean
): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }

  if (typeof value === "number") {
    return value.toFixed(2);
  }

  return value ? "True" : "False";
}

console.log(displayValue("typescript"));
console.log(displayValue(42));
console.log(displayValue(true));

TypeScript narrows value to string in the first branch, number in the second, and boolean in the remaining branch. Each branch can then use operations appropriate for its narrowed type.

One JavaScript detail is important: typeof null returns "object". Therefore, typeof alone cannot distinguish null from other object values. When validating an object, explicitly check that the value is not null before accessing its properties.

function isObjectValue(
  value: unknown
): boolean {
  return typeof value === "object" && value !== null;
}

console.log(isObjectValue({ name: "Asha" }));
console.log(isObjectValue(null));
console.log(isObjectValue("TypeScript"));

12. Primitive Types vs Wrapper Objects

TypeScript distinguishes primitive types such as string, number, and boolean from their corresponding object wrapper types String, Number, and Boolean. For normal application code, use the lowercase primitive types.

let courseName: string = "TypeScript";
let price: number = 49.99;
let published: boolean = true;

console.log(courseName);
console.log(price);
console.log(published);

The primitive types represent ordinary JavaScript string, number, and Boolean values. The capitalized wrapper types describe boxed objects and are rarely appropriate as annotations for everyday variables.

Using primitive annotations keeps function contracts and assignments aligned with common JavaScript values. Avoid constructing wrapper objects such as new String("hello") unless a specialized API genuinely requires them.

13. Type Conversion Is Different from Type Annotation

A type annotation communicates an expected type to the compiler, while type conversion changes or interprets a runtime value. These operations solve different problems and should not be confused.

const input = "42";

const numericValue: number = Number(input);

console.log(numericValue);
console.log(numericValue + 8);

Number(input) performs a runtime conversion, producing a numeric value for this input. The number annotation describes the expected type of the resulting variable.

Conversion can fail to produce a meaningful numeric result. For example, Number("hello") returns NaN rather than throwing an error. Validate converted values when the application depends on valid numeric input.

function parsePositiveNumber(
  input: string
): number | undefined {
  const value = Number(input);

  if (!Number.isFinite(value) || value <= 0) {
    return undefined;
  }

  return value;
}

console.log(parsePositiveNumber("42"));
console.log(parsePositiveNumber("hello"));
console.log(parsePositiveNumber("-5"));

This example converts the input and validates that the result is finite and positive. Returning undefined makes invalid input an explicit possibility that callers can handle.

Common Primitive Type Mistakes

Using capitalized wrapper types

Prefer string, number, and boolean instead of String, Number, and Boolean for ordinary variables and function parameters.

Confusing type annotations with conversions

An annotation does not change the runtime value. Use explicit conversion and validation when data needs to be transformed into another type.

Ignoring null and undefined

When these values are permitted, model them in the type and check them before performing operations that require a non-missing value.

Mixing number and bigint operations

BigInt and number values generally cannot be combined directly in arithmetic expressions. Convert values deliberately and consider whether precision can be lost.

Assuming type annotations validate external values

TypeScript annotations do not verify incoming API data at runtime. Validate external input before relying on its declared structure or primitive type.

Best Practices for Primitive Types

  • Use string, number, and boolean for ordinary primitive values.
  • Allow type inference to handle obvious local values when it keeps code readable.
  • Use literal types and unions when a value must belong to a defined set of choices.
  • Model null and undefined explicitly when they are valid application states.
  • Choose bigint only when the application needs integer precision beyond ordinary number capabilities.
  • Use symbol when unique symbol identity or symbol-based keys are appropriate.
  • Prefer unknown over any when the actual type has not been established.
  • Validate external data at runtime and handle conversion failures deliberately.

Conclusion

Primitive types form the foundation of TypeScript's type system. String, number, and boolean represent the most common application values, while bigint, symbol, null, and undefined support additional runtime values and use cases.

By understanding primitive annotations, type inference, literal types, null handling, and runtime conversion, you can write functions and variables with clearer contracts. These fundamentals prepare you for more advanced concepts such as arrays, tuples, object types, unions, interfaces, and generics.

Code Examples

String, Number, and Boolean

typescript
const username: string = "Asha";
const age: number = 25;
const isActive: boolean = true;

console.log(username);
console.log(age);
console.log(isActive);

// Compile-time error:
// age = "twenty-five";
    

These are the most common primitive types in TypeScript. They describe text, numeric values, and true-or-false states.

BigInt Values

typescript
const largeNumber: bigint = 9007199254740993n;
const additionalValue: bigint = 100n;

const result = largeNumber + additionalValue;

console.log(largeNumber);
console.log(result);
    

BigInt represents integers beyond the reliable integer precision of ordinary numbers. Use an appropriate JavaScript target and runtime that support BigInt.

Unique Symbol Values

typescript
const firstId: symbol = Symbol("id");
const secondId: symbol = Symbol("id");

console.log(firstId === secondId);

const record = {
  [firstId]: 101
};

console.log(record[firstId]);
    

Each Symbol() call creates a unique symbol. Symbols can be used as object keys when unique identity is useful.

Handle null and undefined

typescript
function getDisplayName(
  name: string | null | undefined
): string {
  return name ?? "Guest";
}

console.log(getDisplayName("Asha"));
console.log(getDisplayName(null));
console.log(getDisplayName(undefined));
    

Union types can represent missing values explicitly. Nullish coalescing provides a fallback only for null and undefined.

Convert and Validate Numeric Input

typescript
function parsePositiveNumber(
  input: string
): number | undefined {
  const value = Number(input);

  if (!Number.isFinite(value) || value <= 0) {
    return undefined;
  }

  return value;
}

console.log(parsePositiveNumber("42"));
console.log(parsePositiveNumber("hello"));
console.log(parsePositiveNumber("-5"));
    

A type annotation does not convert input text to a number. Convert the value at runtime, then validate the result before treating it as a valid positive number.

Pro Tip

Use lowercase primitive types such as string, number, and boolean. Let TypeScript infer obvious local types, explicitly model null and undefined when permitted, and remember that annotations do not convert or validate runtime values.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.