typescript
/

TypeScript Variables

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

typescript

TypeScript Variables

What are Variables?

Variables are used to store data values in TypeScript, with optional type annotations for better safety.

Variable Declarations

TypeScriptRead-only
1
let name: string = 'John';
const age: number = 30;
var isActive: boolean = true;

let vs const vs var

KeywordScopeReassignUsage
letBlockYesPreferred for variables
constBlockNoConstants
varFunctionYesAvoid using

Type Annotations

TypeScriptRead-only
1
let score: number = 100;
let username: string = 'Admin';

Type Inference

TypeScriptRead-only
1
let city = 'Chennai'; // inferred as string

Multiple Variables

TypeScriptRead-only
1
let a: number = 10, b: number = 20;

Undefined & Null

TypeScriptRead-only
1
let value: undefined = undefined;
let data: null = null;

Best Practices

  • Prefer const for fixed values
  • Use let instead of var
  • Add types for clarity
  • Use meaningful variable names

Common Mistakes

  • Using var unnecessarily
  • Overusing any type
  • Incorrect type assignment
  • Not using const when needed

Conclusion

TypeScript variables enhance code safety and readability by combining JavaScript variable declarations with type annotations.

Try it yourself

let name: string = 'TypeScript';
console.log(name);

Test Your Knowledge

Q1
of 3

Which is block scoped?

A
var
B
let
C
function
D
class
Q2
of 3

Cannot reassign?

A
let
B
var
C
const
D
any
Q3
of 3

Avoid using?

A
let
B
const
C
var
D
string

Frequently Asked Questions

What is let?

A block-scoped variable.

What is const?

A constant variable that cannot be reassigned.

Should we use var?

No, it is outdated and should be avoided.

Previous

ts types

Next

ts type inference

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.