Programming Languages

TypeScript unknown: Check an Input before You Use It

SoftwareJobs.io editorial1 December 20262 min read

A value from outside your code may not have the shape you expect. TypeScript unknown lets you represent that uncertainty while requiring checks before type-specific operations. It does not automatically validate incoming data for you.

Start with a small function

function readName(value: unknown): string {
  if (typeof value !== "string") {
    throw new Error("Name must be text");
  }
  return value.trim();
}

After the check, TypeScript understands that value is a string. With any, unsupported operations could pass the type checker without this evidence. The TypeScript Handbook explains unknown as a safer way to describe a value whose type has not yet been established.

Separate type from business validity

An empty string still passes the string check. If a name must contain text after trimming, that needs another rule. Similarly, checking that an input is an object is not proof that all required fields exist or have valid values. Decide which conditions the feature actually needs.

Try useful inputs

  • A normal string with surrounding spaces.
  • An empty string.
  • A number.
  • Null.
  • An object with a name property.

Write the expected result for each before running the function. The object case should not be accepted merely because it looks related to the task.

Explain the boundary

For a Malta developer interview, describe where untrusted or uncertain data enters the application and how you establish its usable form. A type assertion alone is not evidence that a runtime value meets your requirements.

Sources and further reading

Browse current technology jobs in Malta →

PUT YOUR IDEAS INTO ACTION

What’s your next move?

Explore software, cloud and data roles that fit your skills and ambitions.

Explore opportunities
KEEP EXPLORING

More ideas for your next chapter