1. What are the primitive
types in TypeScript?
TypeScript has three
primitive types that are frequently used: string, number, and boolean. These
correspond to the similarly named types in JavaScript.
2. What is TypeScript ?
TypeScript
files use a .ts extension, in contrast to the .js extension used by the
JavaScript files. Since TypeScript is a superset of JavaScript, all valid
JavaScript code is a valid TypeScript code, and renaming a .js file to .ts
won’t change anything.
Typescript
compiler generates vanilla JavaScript that gets executed.
3. Explain
how the arrays work in TypeScript
Here is the syntax to
declare and initialize an array in TypeScript.
let
values: number[] = [];
values[0]
= 10;
values[1]
= 20;
values[2]
= 30;
You can also create an
array using the short-hand syntax as follows:
let
values: number[] = [15, 20, 25, 30];
TypeScript provides an
alternate syntax to specify the Array type.
let
values: Array<number> = [15, 20, 25, 30];
4.
What is any type, and when to use it ?
There are times when you want to store a
value in a variable but don’t know the type of that variable in advance. For
example, the value is coming from an API call or the user input. The ‘any’ type
allows you to assign a value of any type to the variable of type any.
let person: any = "Foo";
5. What is void, and when to use the void type?
function
notify(): void {
alert("The user has been notified.");
}
If
a variable is of type void, you can only assign the null or undefined values to
that variable.
6. What is an unknown type, and when to use it in TypeScript?
The unknown type is the
type-safe counterpart of any type. You can assign anything to the unknown, but
the unknown isn’t assignable to anything but itself and any, without performing
a type assertion of a control-flow-based narrowing. You cannot perform any
operations on a variable of an unknown type without first asserting or
narrowing it to a more specific type.
Consider the following example. We create the foo variable of unknown type and assign a string value to it. If we try to assign that unknown variable to a string variable bar, the compiler gives an error.
let foo: unknown = "Akshay";
// Type 'unknown' is not assignable to type 'string'.(2322)
let bar: string = foo as string;
7.What are the different keywords to declare
variables in TypeScript?
var: Declares a function-scoped or global variable. You can optionally set its value during the declaration. Its behavior and scoping rules are similar to the var keyword in JavaScript. For example,
var
foo = "bar";
let: Declares a block-scoped local
variable. Similar to var, you can optionally set the value of a variable during
the declaration. For example,
let
a = 5;
if
(true) {
let a = 10;
console.log(a); // 10
}
console.log(a);
// 5
const: Declares a block-scoped constant value
that cannot be changed after it’s initialized. For example,
const
a = 5;
if
(true) {
a = 10; // Error: Cannot assign to 'a' because it is a constant.(2588)
}
8. Provide the syntax of a function with the type annotations.
Here’s
the TypeScript syntax to create and call a function.
function
greet(name: string): string {
return `Hello, ${name}`;
}
let greeting = greet("Anders");
console.log(greeting);
// "Hello, Anders"
9. How to specify optional properties in TypeScript?
let
pt : { x: number; y: number; z?: number } = {
x: 10,
y: 20
};
console.log(pt);
In
the example above, because the property ‘z’ is marked as optional, the compiler
won’t complain if we don’t provide it during the initialization.
10. Explain the purpose of the never type in
TypeScript.
In TypeScript,
the never type represents a
type that indicates a value that will never occur. It's used to indicate
scenarios where a function will never return or where a value cannot have any
possible value, effectively representing the absence of a value.
11. What is enum in Typescript ?
an enum (short for "enumeration") is a way to define a set of named constant values.
enum Team {
Alpha,
Beta,
Gamma,
Delta
}
let t: Team = Team.Delta;
12 What
is the typeof operator? How is it used in TypeScript?
Similar to JavaScript, the typeof operator in TypeScript returns the type of the operand
13. What are the rest parameters and arguments in TypeScript?
A rest parameter allows a function to accept an indefinite number of arguments as an array. It is denoted by the ‘…’ syntax and indicates that the function can accept one or more arguments.
function
add(...values: number[]) {
let sum = 0;
values.forEach(val => sum += val);
return sum;
}
const
sum = add(5, 10, 15, 20);
console.log(sum);
// 50
14. Explain the TypeScript class syntax.
Here is a simple class that defines an Employee type.
class
Employee {
name: string;
salary: number;
constructor(name: string, salary: number) {
this.name = name;
this.salary = salary;
}
promote() : void {
this.salary += 10000;
}
}
You can create an instance (or object) of a class by using
the new keyword.
//
Create a new employee
let
john = new Employee("John", 60000);
console.log(john.salary);
// 60000
john.promote();
console.log(john.salary);
// 70000
15. Explain the arrow function syntax in
TypeScript.
Consider a regular function that adds two numbers and returns a number.
function
add(x: number, y: number): number {
let sum = x + y;
return sum;
}
Using arrow functions syntax, the same function can be
defined as:
let
add = (x: number, y: number): number => {
let sum = x + y;
return sum;
}
16. Provide the syntax for optional
parameters in TypeScript.
function greet(name: string, greeting?: string) {
if (!greeting)
greeting =
"Hello";
console.log(`${greeting}, ${name}`);
}
greet("John", "Hi"); // Hi, John
greet("Mary", "Hola"); // Hola, Mary
greet("Jane"); // Hello, Jane
17. What
is the purpose of the tsconfig.json file?
A
tsconfig.json file in a directory marks that directory as the root of a
TypeScript project. It provides the compiler options to compile the project.
Here is a sample tsconfig.json file:
{ "compilerOptions": { "module": "system", "noImplicitAny": true, "removeComments": true, "outFile": "../../built/local/tsc.js", "sourceMap": true }, "include": ["src/**/*"], "exclude": ["node_modules", "**/*.spec.ts"]}
18. Explain the different variants of
the for loop in TypeScript.
TypeScript
provides the following three ways to loop over collections.
·
‘for’ loop
·
·
‘forEach’ function
·
·
·
‘for..of’ statement
19. Explain the symbol type in TypeScript.
You can create symbol
values by calling the Symbol() constructor, optionally providing a string key.
let foo = Symbol();
let bar = Symbol("bar");
// optional string key
A key characteristic
of symbols is that they are unique and immutable.
let foo =
Symbol("foo");
let newFoo =
Symbol("foo");
let areEqual = foo ===
newFoo;
console.log(areEqual);
// false, symbols are unique
20. Explain how optional chaining works
in TypeScript.
Using optional chaining, the following expression
let x = foo === null || foo === undefined ? undefined :
foo.bar.baz();
can be expressed as:
let x = foo?.bar.baz();
21. What is meant by type inference?
TypeScript can infer
the type of a variable when you don’t provide an explicit type. This is known
as type inference. This is usually done when the variables or parameters are
initialized during the declaration.
For example,
TypeScript knows that the variable foo is a string, even though we don’t
mention string as a type.
let foo = "this
is a string";
console.log(typeof
foo); // "string"
22. What is an interface?
In TypeScript, you can
create and use an interface as follows:
interface Employee {
name: string;
salary: number;
}
function process(employee: Employee) {
console.log(`${employee.name}'s salary =
${employee.salary}`);
}
let john: Employee = {
name: "John Doe",
salary: 150000
}
process(john); // "John Doe's salary = 150000"
23. Does TypeScript support static
classes? If not, why?
TypeScript
doesn’t support static classes, unlike the popular object-oriented programming
languages like C# and Java.
These
languages need static classes because all code, i.e., data and functions, need
to be inside a class and cannot exist independently. Static classes provide a
way to allow these functions without associating them with any objects.
In
TypeScript, you can create any data and functions as simple objects without
creating a containing class. Hence TypeScript doesn’t need static classes. A
singleton class is just a simple object in TypeScript
24. What are anonymous functions? Provide their syntax in TypeScript.
An anonymous function is a function without a name.
Anonymous functions are typically used as callback functions, i.e., they are
passed around to other functions, only to be invoked by the other function at a
later point in time.
For example,
setTimeout(function
() {
console.log('Run after 2 seconds')
},
2000);
You
can invoke an anonymous function as soon as it’s created. It’s called
‘immediately invoked function execution (IIFE)’,
For
example:
(function()
{
console.log('Invoked
immediately after creation');
})();
25. What are union types in TypeScript?
A union type is a
special construct in TypeScript that indicates that a value can be one of
several types. A vertical bar (|) separates these types.
let value: string | number = "Foo";
value = 10; // Okay
However, if we try to
set the value to a type not included in the union types, we get the following
error.
value = true; // Type 'boolean' is not assignable to type
'string | number'.(2322)
26. What are intersection types?
Intersection types let
you combine the members of two or more types by using the ‘&’ operator.
This allows you to combine existing types to get a single type with all the
features you need.
The following example
creates a new type Supervisor that has the members of types Employee and
Manager.
interface Employee {
work: () => string;
}
interface Manager {
manage: () => string;
}
type Supervisor
= Employee & Manager;
// john can both
work and manage
let john: Supervisor;
27. What are type aliases? How do you create one?
Type aliases give a
new, meaningful name for a type. They don’t create new types but create new
names that refer to that type.
For example, you can
alias a union type to avoid typing all the types everywhere that value is being
used.
type alphanumeric =
string | number;
let value:
alphanumeric = "";
value = 10;
28. Explain the tuple types in TypeScript.
Tuples are a special
type in TypeScript. They are similar to arrays with a fixed number of elements
with a known type. However, the types need not be the same.
// Declare a tuple
type and initialize it
let values: [string,
number] = ["Foo", 15];
// Type 'boolean' is not assignable to type 'string'.(2322)
// Type 'string' is
not assignable to type 'number'.(2322)
let wrongValues:
[string, number] = [true, "hello"]; // Error
Since TypeScript 3.0,
a tuple can specify one or more optional types using the ? as shown below.
let values: [string,
number, boolean?] = ["Foo", 15]
29. Explain how tuple destructuring works in TypeScript.
let employeeRecord:
[string, number] = ["John Doe", 50000];
let [emp_name,
emp_salary] = employeeRecord;
console.log(`Name:
${emp_name}`); // "Name: John Doe"
console.log(`Salary:
${emp_salary}`); // "Salary: 50000"
After destructuring,
you can’t assign a value of a different type to the destructured variable. For
example,
emp_name = true;
// Type 'boolean' is not assignable to type 'string'.(2322)
30. What are type assertions in
TypeScript?
Sometimes, you as a
programmer might know more about the type of a variable than TypeScript can
infer. Usually, this happens when you know the type of an object is more
specific than its current type. In such cases, you can tell the TypeScript
compiler not to infer the type of the variable by using type assertions.
TypeScript provides
two forms to assert the types.
·
as syntax:
let
value: unknown = "Foo";
let
len: number = (value as string).length;
·
<> syntax:
let
value: unknown = "Foo";
let
len: number = (<string>value).length;
31. How to make object properties immutable in TypeScript? (hint: readonly)
You can mark object
properties as immutable by using the readonly keyword before the property name.
For example:
interface Coordinate {
readonly x: number;
readonly y: number;
}
When you mark a
property as readonly, it can only be set when you initialize the object. Once
the object is created, you cannot change it.
let c: Coordinate = {
x: 5, y: 15 };
c.x = 20; // Cannot
assign to 'x' because it is a read-only property.(2540)
32. What are triple-slash directives?
Triple-slash
directives are single-line comments that contain a single XML tag. TypeScript
uses this XML tag as a compiler directive.
You can
only place a triple-slash directive at the top of the containing file. Only
single or multi-line comments can come before a triple-slash directive.
TypeScript treats them as regular comments if it occurs in the middle of a code
block, after a statement.
The
primary use of triple-slash directives is to include other files in the
compilation process. For example, the following directive instructs the
compiler to include a file specified by the path in the containing TypeScript
file.
///
<reference path="..." />
Triple-slash
directives also order the output when using --out or --outFile. The output
files are produced to the output file location in the same order as the input
files
33. Explain the purpose of the ‘in’ operator.
const
car = { make: 'Hyundai', model: 'Elantra', year: 2017 };
console.log('model'
in car); // true
console.log('test'
in car); // false
No comments:
Post a Comment