Tutorials Logic, IN info@tutorialslogic.com

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

TypeScript 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.

Add one worked example that compares the normal path with the boundary case for TypeScript Basic Types: string, number, boolean, null and undefined.

Keep the note tied to a real TypeScript workflow so the idea is easier to recall later.

TypeScript Basic Types string number boolean null and undefined should be studied as a practical TypeScript lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

What Are Basic Types?

Type Example Value Common Use
string "admin" Names, emails, messages, slugs
number 42 Prices, counts, scores, IDs
boolean true Flags, toggles, yes/no state
null null Intentional empty value
undefined undefined Value not provided yet

Primitive Types

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

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

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

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

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.

Type Meaning Advice
any Skip type checking Avoid when possible
unknown Value exists but type is not known yet Check before use
never No possible value Useful for exhaustive checks

Safer Unknown Values

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"]);

TypeScript Basic Types string number boolean null and undefined in Real Work

TypeScript Basic Types string number boolean null and undefined matters in TypeScript because it changes how a program is written, tested, or debugged. The page should explain the normal flow first: what the developer writes, what the runtime or platform does, and what result should appear.

When teaching TypeScript Basic Types string number boolean null and undefined, avoid stopping at syntax. Show the surrounding decision: why this feature is chosen, what problem it removes, and what would become harder if the feature were not used.

  • Identify the concrete problem solved by TypeScript Basic Types string number boolean null and undefined.
  • Show the normal input, operation, and output for typescript.
  • Mention the nearby alternative a beginner may confuse with this topic.
  • Tie the explanation to a real project task, command, component, query, or debugging step.

TypeScript Basic Types string number boolean null and undefined normal path trace

TypeScript Basic Types string number boolean null and undefined normal path trace
1. Define the input for TypeScript Basic Types string number boolean null and undefined.
2. Apply the rule from the lesson.
3. Compare the actual result with the expected result.
4. Record the fix if the result differs.

TypeScript Basic Types string number boolean null and undefined edge path trace

TypeScript Basic Types string number boolean null and undefined edge path trace
1. Try empty, missing, duplicate, or invalid data.
2. Identify where TypeScript Basic Types string number boolean null and undefined changes behavior.
3. Explain the safest correction.
4. Retest the normal path.
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.
Common Mistakes to Avoid
WRONG Memorizing TypeScript Basic Types string number boolean null and undefined without the situation where it is useful.
RIGHT Connect TypeScript Basic Types string number boolean null and undefined to a concrete TypeScript task.
Purpose makes syntax easier to recall.
WRONG Testing TypeScript Basic Types string number boolean null and undefined only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to TypeScript Basic Types string number boolean null and undefined.
Evidence keeps debugging focused.
WRONG Memorizing TypeScript Basic Types string number boolean null and undefined without the situation where it is useful.
RIGHT Connect TypeScript Basic Types string number boolean null and undefined to a concrete TypeScript task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to TypeScript Basic Types: string, number, boolean, null and undefined, then fix it and explain the fix.
  • Summarize when to use TypeScript Basic Types: string, number, boolean, null and undefined and when another approach is better.
  • Write a small example that uses TypeScript Basic Types string number boolean null and undefined in a realistic TypeScript scenario.
  • Change one important value in the TypeScript Basic Types string number boolean null and undefined example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in TypeScript, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

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