Type Inference in Action
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 10 of 73.
When you initialize a variable with a value, TypeScript examines that value and automatically assigns the appropriate type:
let message = "Hello, World!"; // TypeScript infers: string
let count = 42; // TypeScript infers: number
let isActive = true; // TypeScript infers: booleanThis type inference provides the same type safety as explicit annotations, but with cleaner, more readable code. TypeScript will still catch type errors if you try to reassign these variables to incompatible values.
Type inference works because TypeScript analyzes the initial value at the moment of assignment. A string value tells TypeScript the variable should be of type string, a numeric value indicates number, and so on.
Challenge
EasyCreate three variables using TypeScript's type inference without explicit type annotations:
Declare a variable named companyName and initialize it with the string "TechCorp".
Declare a variable named employeeCount and initialize it with the number 150.
Declare a variable named isPublic and initialize it with the boolean value false.
Print all three variables to the console on separate lines in the order they were declared.
TypeScript will automatically infer the correct types based on the initial values you assign to each variable.
Try it yourself
// TODO: Write your code here
// Declare the three variables with their initial values
// Remember to use TypeScript's type inference (no explicit type annotations needed)
// Print all three variables to the consoleThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples