Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Declaring Typed Variables with let and const

Recommended resources

Hello! Last time, you built a TypeScript file and ran the resulting JavaScript in Node.js. The example already contained typed variables; now you’ll decide how to declare them yourself. This lesson focuses on three everyday value types—string, number, and boolean—and on choosing const or let according to whether a variable needs to be reassigned.

These decisions are small, but they come up constantly in backend code: a membership status is text, a retry count is numeric, and a verification flag is either true or false. Being able to write and explain those declarations without assistance is a useful foundation for the functions you’ll write next.


Name the kind of value

A string is text, such as "pending". A number can be a whole number or a decimal; TypeScript does not have separate int and float types for ordinary JavaScript numbers. A boolean is true or false—not the strings "true" and "false".

const status: string = "pending"
const price: number = 12.5
const isActive: boolean = false

The pattern is name: type = value. The type annotation describes which values TypeScript will accept for that variable. Use the lowercase type names shown here.

Watch the first part of Net Ninja’s TypeScript Tutorial #3 - Type Basics to see these value types identified in code.

TypeScript Tutorial #3 - Type Basics

Net Ninja’s TypeScript Tutorial #3 - Type Basics shows how TypeScript recognizes string, number, and boolean values from their initial assignments.

Watch the type basics. Focus on the numeric and boolean declarations, and on why both whole numbers and decimals use number. The video also mentions var; this lesson will use let and const.

For a concise reference, read the primitive-types portion of the TypeScript Handbook.

TypeScript: Documentation - Everyday Types

The TypeScript Handbook states the precise meaning and spelling of the three types you will use in this lesson.

In “The primitives: string, number, and boolean,” read the three primitives, continuing through the true and false examples and the note on lowercase type names. Stop before “Arrays.”



Let TypeScript infer a type—or state it explicitly

You do not have to annotate every variable. When you write let attempts = 3, TypeScript can infer number from the initial value. It will accept a later number but report a type error if you try to assign text:

let attempts = 3
attempts = 2        // Accepted
// attempts = "two" // Type error: a string is not assignable to number

An explicit annotation makes the intended type visible in the declaration:

let attempts: number = 3

For this example, both forms protect later assignments in the same way. An annotation is particularly useful when you want to state the intended type before there is an initial value:

let status: string
status = "pending"

Do not read or use status before assigning it. In ordinary code, initializing a variable when you declare it is often easier to reason about.

The second part of Type Basics demonstrates accepted and rejected reassignments. Then watch Net Ninja’s TypeScript Tutorial #5 - Explicit Types for the colon syntax.

TypeScript Tutorial #3 - Type Basics

The continuation of TypeScript Tutorial #3 - Type Basics distinguishes changing a variable’s value from assigning it a value of the wrong type.

Watch reassignment and inference. Notice that replacing one string with another is accepted, while replacing it with a number is not.

TypeScript Tutorial #5 - Explicit Types

Net Ninja’s TypeScript Tutorial #5 - Explicit Types demonstrates declarations where the intended type is written before a value is assigned.

Watch explicit declarations. Focus on where : string, : number, and : boolean go, and which later assignments TypeScript rejects.

The Handbook puts both approaches side by side:

TypeScript: Documentation - Everyday Types

The “Type Annotations on Variables” section explains why an initializer often makes an explicit annotation unnecessary.

In “Type Annotations on Variables,” read annotations and inference, then continue through the inferred myName example. Stop before “Functions”; typed functions are the next lesson’s topic.

The distinction to keep: inference does not mean “no type checking.” It means TypeScript worked out a type without requiring you to write it.



Choose const or let for the binding

A type answers, “What kind of value belongs here?” The declaration keyword answers a different question: “Will this variable be assigned a new value?”

Use const when you do not plan to reassign the variable. Use let when you do. This example needs both:

const planName: string = "starter"
let remainingAttempts: number = 3
let isVerified: boolean = false

remainingAttempts = 2
isVerified = true

console.log(planName, remainingAttempts, isVerified)

The output is:

starter 2 true

remainingAttempts and isVerified can change because they were declared with let; their new values still have to match their types. planName cannot be reassigned, even to another string, because it was declared with const:

// planName = "premium" // Error: cannot assign to a const variable

These are different errors. Assigning "two" to remainingAttempts violates its number type. Assigning "premium" to planName violates its const binding, despite "premium" being a string.

The TypeScript Handbook recommends choosing const for declarations you do not intend to reassign. Read its rule, but leave its object-mutation example for the later lesson on objects and references.

Documentation - Variable Declaration

The TypeScript Handbook separates the rule for a const binding from the practical choice between let and const.

Under “const declarations,” start with the paragraph beginning “They are like let declarations” and read the binding rule through its warning that the referenced value is not necessarily immutable. Skip the object example for now. Then, under “let vs. const,” read the selection rule. Stop before “Destructuring.”



See the compiler enforce your declarations

Use the same project workflow as the previous lesson. Put the complete, working planName example above in src/main.ts, then run npm run build followed by npm start. Compare the terminal output with the three values passed to console.log.

Next, make one temporary change at a time:

remainingAttempts = "two"

Build and read the type error. Restore the numeric assignment, then temporarily try:

planName = "premium"

Build again and compare the error: this time the problem is reassignment of a const, not the value’s type. Remove the temporary line and rebuild successfully before running the program again. With the project’s noEmitOnError setting, a failed build does not generate new JavaScript; an older file in dist may still exist.

Finally, you can remove the three explicit annotations while keeping the initial values:

const planName = "starter"
let remainingAttempts = 3
let isVerified = false

TypeScript still has enough information to check the later assignments. This is usually the shorter way to write declarations with clear initial values.

As in the earlier lesson, these checks happen while TypeScript analyzes the source. The annotations do not become runtime validation in the JavaScript that Node.js executes.



Conclusion

Use string for text, number for numeric values, and boolean for true or false. TypeScript can infer these from initial values, or you can write an annotation after the variable name. Separately, choose const when the variable will not be reassigned and let when it will; let does not permit assignments that violate the variable’s type.

Next, you’ll use these same types to describe a function’s inputs and return value.