TypeScript can determine variable and function return types automatically through type inference, or allow developers to specify them explicitly using type annotations.
flowchart TD
A["Variable Assignment / Function Return"] --> B{"Explicit Annotation Present?"}
B -- "Yes" --> C["Compiler Enforces Explicit Type"]
B -- "No" --> D["Compiler Analyzes Initializer Value"]
D --> E["Infers Most Specific Common Type"]
let score: number = 100;).let score = 100; infers number).// Automatic type inference (TypeScript infers string[])
const techStack = ["TypeScript", "Node.js", "PostgreSQL"];
// TypeScript automatically infers return type as boolean
function isProductionEnvironment(envName: string) {
return envName.toLowerCase() === "production";
}
// Explicit annotation required when declaring uninitialized variables
let sessionToken: string;
if (isProductionEnvironment("production")) {
sessionToken = "prod_token_991823";
} else {
sessionToken = "dev_token_000000";
}
console.log(`Active Token: ${sessionToken}`);
let Without Annotation: Writing let data; infers any, which disables type safety. Write let data: string | undefined; instead.Write a function multiply(a: number, b: number) without specifying a return type annotation. Inspect what type TypeScript infers for the return value.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With