> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Syntax Variables and Primitives in TypeScript

> Overview of TypeScript variable declarations, primitive types, explicit typing, and type inference demonstrated via a simple duck pond example

This guide covers the core TypeScript syntax you'll use when writing infrastructure and application code: variable declarations, primitive types, explicit typing, and type inference. We'll follow a practical example — Elmer Codde building a small TypeScript app to manage the ducks on his pond — to demonstrate the concepts in context.

Project layout (example in the lab)

```bash theme={null}
EXPLORER
CODE
.vscode
.prettierrc
.profile
.yarnrc.yml
index.ts
package.json
tsconfig.json
yarn.lock

root in ~/code via ⬢ v20.17.0 on ⬢ (us-east-1)
❯
```

The lab environment already has TypeScript installed and configured, and the project is ready to run.

Example TypeScript definitions for the duck app (enums, union type, interface, and a simple class that implements the interface):

```typescript theme={null}
// Enum for Duck Types
enum DuckType {
  Mallard = "Mallard",
  Muscovy = "Muscovy",
  Pekin = "Pekin",
}

// Type for Duck Colors using a union type
type DuckColor = "White" | "Brown" | "Black" | "Mixed";

// Interface for a Duck's properties
interface IDuck {
  name: string; // Name of the duck
  age: number; // Age of the duck in years
  type: DuckType; // Type of duck, using the DuckType enum
  color: DuckColor; // Color of the duck, using the DuckColor union type
  favoriteToy?: string; // Optional property: favorite toy of the duck
}

// Simple PondDuck class that implements the IDuck interface
class PondDuck implements IDuck {
  constructor(
    public name: string,
    public age: number,
    public type: DuckType,
    public color: DuckColor,
    public favoriteToy?: string
  ) {}

  quack(): void {
    console.log(`${this.name} says "quack"!`);
  }

  fly(): void {
    console.log(`${this.name} takes off!`);
  }

  land(): void {
    console.log(`${this.name} lands on the pond.`);
  }
}
```

If you want to follow along locally in the lab environment:

```bash theme={null}
# Install dependencies (run once when you open the project)
yarn install

# Start the development build/watch process
yarn dev
```

A simple runtime example:

```typescript theme={null}
console.log("Let's go!!");
```

When the dev process is running, changes to files restart compilation and show runtime logs automatically.

Meet Elmer Codde: he's building an app to manage ducks on his pond. The app will include common actions such as making ducks quack, fly, and land. The first step is storing basic information about each duck (name, age, type, color).

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/q_P6afvbRoHuV6uC/images/CDK-for-Terraform-with-TypeScript/Introduction-to-TypeScript/Syntax-Variables-and-Primitives-in-TypeScript/elmer-code-manage-pond-ducks.jpg?fit=max&auto=format&n=q_P6afvbRoHuV6uC&q=85&s=3344d1635be272803a9d4ff5d85ae40c" alt="A slide titled &#x22;Elmer – Introduction&#x22; shows a developer icon labeled &#x22;Elmer Code&#x22; with a speech bubble &#x22;Build an app.&#x22; An arrow labeled &#x22;Manage&#x22; points to a blue &#x22;Pond&#x22; containing nine circular duck icons, each labeled &#x22;duck.&#x22;" width="1920" height="1080" data-path="images/CDK-for-Terraform-with-TypeScript/Introduction-to-TypeScript/Syntax-Variables-and-Primitives-in-TypeScript/elmer-code-manage-pond-ducks.jpg" />
</Frame>

## Variables in TypeScript

TypeScript builds on JavaScript's `const`, `let`, and `var` keywords but adds static typing. Best practice is to prefer `const` and `let` over `var`.

| Keyword |                          Mutability | When to use                                | Example                             |
| ------- | ----------------------------------: | ------------------------------------------ | ----------------------------------- |
| `const` | Immutable binding (no reassignment) | For values that should never be reassigned | `const duckName: string = "Daffy";` |
| `let`   |                     Mutable binding | For values that will change over time      | `let duckAge: number = 3;`          |
| `var`   |            Function-scoped, hoisted | Legacy code only — avoid in modern TS/JS   | `var legacyDuck = "Old";`           |

Examples

Explicit typing with `const` (cannot be reassigned):

```typescript theme={null}
const duckName: string = "Daffy";
const duckAge: number = 3;

console.log(duckName); // Output: Daffy
```

Attempting to reassign a `const` triggers a compile-time error:

```typescript theme={null}
const duckAge: number = 3;
// duckAge = 4; // Error: Cannot assign to 'duckAge' because it is a constant.
```

Using `let` allows reassignment:

```typescript theme={null}
let mutableDuckName: string = "Daffy";
let mutableDuckAge: number = 3;

mutableDuckAge = 4; // OK
mutableDuckName = "Donald"; // OK

console.log(mutableDuckName, mutableDuckAge); // Output: Donald 4
```

## Explicit typing vs. type inference

TypeScript supports both explicit annotations and inference. When the type is obvious from the initializer, you can omit the annotation and let the compiler infer the type.

* Explicit typing: you declare variable types directly.
* Type inference: TypeScript infers the variable's type from its initial value and enforces it afterward.

Examples:

```typescript theme={null}
// Explicit typing
let duckType: string = "Mallard";

// Type inference (inferred as string)
let duckColor = "Black";

// The following assignment would cause a type error because duckColor is inferred as a string:
// duckColor = 1; // Error: Type 'number' is not assignable to type 'string'.
```

<Callout icon="lightbulb" color="#1CB2FE">
  Tip: Use explicit types for public APIs, exported values, and complex structures. For local variables with obvious initial values, type inference keeps code concise while preserving type safety.
</Callout>

## Quick checklist: variables & primitives

* Prefer `const` for values that won't be reassigned.
* Use `let` for mutable bindings.
* Avoid `var` in new code.
* Favor type inference for local, simple values; add explicit types for public interfaces and complex values.
* The TypeScript compiler enforces types at build time, reducing runtime type errors.

That concludes this focused overview of variables and primitives in TypeScript. Continue to the next section to learn about Arrays & Objects and how to model collections of ducks.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/q_P6afvbRoHuV6uC/images/CDK-for-Terraform-with-TypeScript/Introduction-to-TypeScript/Syntax-Variables-and-Primitives-in-TypeScript/programming-course-7-step-variables-highlight.jpg?fit=max&auto=format&n=q_P6afvbRoHuV6uC&q=85&s=c105ccf2b5d5706704cdc3f2fa7fbe28" alt="A horizontal seven-step timeline for a programming course with numbered circular nodes; step 01 &#x22;Variables & Parameters&#x22; is highlighted. The other nodes read Arrays & Objects, Types & Interfaces, Functions, Classes, Union Types & Enums, and Putting it All Together (© KodeKloud)." width="1920" height="1080" data-path="images/CDK-for-Terraform-with-TypeScript/Introduction-to-TypeScript/Syntax-Variables-and-Primitives-in-TypeScript/programming-course-7-step-variables-highlight.jpg" />
</Frame>

## Links and references

* [TypeScript Handbook — Basic Types](https://www.typescriptlang.org/docs/handbook/basic-types.html)
* [TypeScript Documentation](https://www.typescriptlang.org/docs/)
* [KodeKloud Labs — Learning Environment](https://kodekloud.com/)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/cdk-for-terraform-with-typescript/module/eb523de4-1aeb-429a-820a-20d9f6426562/lesson/9424b931-5259-41ea-a9f9-fca84b8bc920" />
</CardGroup>
