TypeScript Interview Questions and Answers
1. Explain the data types available in TypeScript.
TypeScript provides the following data types:
Built-in Data Types
- string – Stores text values.
number – Stores numeric values.
boolean – StoresTrueorfalse.
null – Represents an empty value.
undefined – Represents an uninitialized variable.
any – Accepts values of any type.
unknown – Stores values of unknown type safely.
void – Used for functions that do not return a value.
never – Used for functions that never return.
User-defined Data Types
- Array – Stores multiple values of the same type.
Tuple – Stores a fixed number of values with different data types.
Enum – Defines a set of named constants.
Class – Creates objects with properties and methods.
Interface – Defines the structure of an object.
Type Alias – Creates a custom name for an existing type.
2. In how many ways can we declare variables in TypeScript?
TypeScript provides three ways to declare variables:
- var – Function-scoped. It can be redeclared and updated. Generally not recommended in modern TypeScript.
- let – Block-scoped. It can be updated but cannot be redeclared within the same scope.
- const – Block-scoped. It cannot be reassigned after initialization.
Code Example
// var
var age = 25;
var age = 30; // Allowed (redeclared)
age = 35; // Allowed (updated)
// let
let name = "Shiv";
name = "Sara"; // Allowed (updated)
// let name = "John"; // Error: Cannot redeclare block-scoped variable
// const
const country = "India";
// country = "USA"; // Error: Cannot reassign a const variable
// Display Output
document.write("Output
");
document.write("age = " + age + "
");
document.write("name = " + name + "
");
document.write("country = " + country);
Comments
Post a Comment