Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

TypeScript Basic Types: string, number, boolean, null and undefined

What Are Basic Types?

TypeScript starts with the same runtime values JavaScript already has: strings, numbers, booleans, arrays, objects, null, undefined, symbols, and bigints. TypeScript adds a type system on top so your editor and compiler can catch incorrect usage before the code runs.

A type describes what kind of value a variable can hold and which operations are safe. If a value is a string, TypeScript allows string methods. If it is a number, TypeScript allows number methods. If you try to mix them incorrectly, TypeScript warns you early.

TypeExample ValueCommon Use
string"admin"Names, emails, messages, slugs
number42Prices, counts, scores, IDs
booleantrueFlags, toggles, yes/no state
nullnullIntentional empty value
undefinedundefinedValue not provided yet
Primitive Types
let username: string = "meera";
let score: number = 92.5;
let isActive: boolean = true;

console.log(username.toUpperCase());
console.log(score.toFixed(1));
console.log(isActive ? "Active" : "Inactive");

// score = "high";
// Error: string is not assignable to number.

Type Inference

You do not need to annotate every variable. TypeScript can infer many types from assigned values. Inference keeps code clean while still giving type safety.

Use explicit annotations when the type is not obvious, when the variable starts empty, or when you want to document a wider type than the initial value.

Inferred Types
const city = "Pune";       // inferred as the literal type "Pune"
let temperature = 31;      // inferred as number
let online = false;        // inferred as boolean

temperature = 29;
online = true;

// online = "yes";
// Error: string is not assignable to boolean.

Literal Types

A literal type is a type that allows one exact value. For example, "success" is more specific than string. Literal types are useful when a variable should only accept known values.

Literal types become powerful when combined with unions. Together, they can model statuses, roles, button variants, routes, payment states, and other controlled choices.

Literal Values
let requestStatus: "idle" | "loading" | "success" | "error";

requestStatus = "loading";
requestStatus = "success";

// requestStatus = "done";
// Error: "done" is not one of the allowed values.

type ButtonSize = "sm" | "md" | "lg";
const size: ButtonSize = "md";

Arrays and Object Basics

Arrays describe repeated values, while objects describe named properties. You will use both constantly in TypeScript applications.

For arrays, write the item type followed by []. For objects, describe each property name and its type. Optional properties use ?.

Simple Array and Object Types
const tags: string[] = ["typescript", "frontend", "web"];
const scores: number[] = [80, 90, 100];

type User = {
  id: number;
  name: string;
  email?: string;
  active: boolean;
};

const user: User = {
  id: 1,
  name: "Asha",
  active: true,
};

null and undefined

null usually means the program intentionally has no value. undefined usually means a value has not been assigned or provided. With strict null checks enabled, TypeScript forces you to handle these cases before using the value.

This is one of TypeScript's most useful safety features because many runtime bugs come from trying to read a property or call a method on a missing value.

Handling Missing Values
type Profile = {
  displayName: string;
  avatarUrl: string | null;
};

function getAvatarLabel(profile: Profile): string {
  if (profile.avatarUrl === null) {
    return "No avatar uploaded";
  }

  return `Avatar: ${profile.avatarUrl}`;
}

function greet(name?: string): string {
  return name ? `Hello ${name}` : "Hello Guest";
}

unknown, any and never

any disables type checking and should be used rarely. It is sometimes needed while migrating old JavaScript code, but leaving too much any removes the main benefit of TypeScript.

unknown is safer because TypeScript forces you to check the value before using it. never represents a value that should not exist, such as an impossible branch or a function that always throws.

TypeMeaningAdvice
anySkip type checkingAvoid when possible
unknownValue exists but type is not known yetCheck before use
neverNo possible valueUseful for exhaustive checks
Safer Unknown Values
function printLength(value: unknown): void {
  if (typeof value === "string") {
    console.log(value.length);
    return;
  }

  if (Array.isArray(value)) {
    console.log(value.length);
    return;
  }

  console.log("Length is not available");
}

printLength("TypeScript");
printLength(["a", "b", "c"]);
Key Takeaways
  • Basic TypeScript types describe JavaScript runtime values more clearly.
  • Let TypeScript infer obvious local variable types.
  • Use literal types and unions for controlled choices such as status, role, and size.
  • Handle null and undefined before using a missing value.
  • Prefer unknown over any for uncertain external data.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.