1. Why is TypeScript?
- TypeScript is a superset of JavaScript. Its emphasis on strong typing and advanced language constructs help us write client and server-side code with fewer errors.
- TypeScript is cross-platform, open source, and compiles to JavaScript that is compatible with every major browser and popular JavaScript framework. Some of the major concepts are functions, interfaces, classes, modules and namespaces, and generics
- The JavaScript language has a handful of types like string, number, and Boolean, but TypeScript lets you define your own types in a very object-oriented manner, and the compiler will then check your code against those types and alert you to problems long before it gets to a production environment. I happen to believe that the addition of types also enables faster development.
- If you're using a TypeScript-aware editor (VSCode), it becomes a lot easier to examine the properties and methods available in custom types, and navigate around your project based on the symbols declared in your code.
2. TypeScript vs JavaScript?
TypeScript |
JavaScript |
TypeScript is
an Object-Oriented programming concept like classes,
interfaces, inheritance, generics, etc. |
JavaScript is a Scripting language |
It has a feature known as Static typing |
It does not have static typing |
TypeScript gives support for modules, generics, ES6 |
JavaScript does not support modules, generics, ES6 |
It supports optional parameter function |
It does not support optional parameter function |
It compiles the code and highlighted errors during the
development time. |
It is interpreted language that's why it highlighted the errors
at runtime. |
In this, number, string are the interface. |
In this, number, string are the objects |
It was developed by Anders Hejlsberg in 2012. |
It was developed by Netscape in 1995. |
3. What are
the advantages of using Typescript?
- TypeScript is fast, simple, and most importantly, easy to learn.
- TypeScript supports development of object-oriented code features such as classes, interfaces, inheritance, generics, etc even with minimal knowledge.
- TypeScript offers an API for DOM manipulation.
- Typescript has very good IDE support, as autocompletion, type checking, and source documentation. Which Help developers save a ton of valuable time.
- TypeScript can be used for both server-side and client-side development alike.
- TypeScript comes with types that make code easier to read and avoid major errors. It is better for the compiler to catch errors than to have things fail at runtime
- TypeScript are one of the best forms of documentation you can have. The function signature is a theorem and the function body is the proof
- TypeScript also has the concept of the namespace by Module defining, which makes it reusable and allow lazy loading.
- TypeScript supports the latest JavaScript features including ECMAScript 2015 and also gives all the benefits of ES6 plus more productivity.
4.What are
the different types supported by TypeScript ?
String: A
string is a series of characters that are stored as UTF-16 Unicode code
Number: It reflects the values of the number form. The numbers are
stored as floating-point values in TypeScript
Boolean: This can have values as true or false
Array: This can be a list of numbers together
Tuple: This data type allows users to create an array where the fixed number
type elements are known but not the same.
Enum: This allows creating a user-defined data type.
Undefined: The Undefined type denotes all uninitialized variables.
Void: A void is the return type of the functions that do not return any
type of value.
Null: Null represents a variable whose value is undefined. It is not
possible to directly reference the null type value itself.
Any: It can be implemented to ensure data value to declare said values.
Never: It represents the data type of values that never occur.
5: What are
TypeScript collections ?
Like
other programing languages Typescript also has support for Collection, like
Map, Set etc.
6: What are
Generics in TypeScript ?
Generics
are a feature of TypeScript, which allows you to take advantage of that type
safety while creating code you can reuse throughout your apps.
Reusable
type-safe code that works with multiple types
May be
functions, interfaces, or classes
Code that accepts type parameters for each instance or invocation
interface DataStructure<T> {
push(newItem: T): void;
pop(): T;
}
class Stack<T> implements DataStructure<T> {
items: Array<T> = [];
push(newItem: T): void {
this.items.push(newItem);
}
pop(): T {
return this.items.pop();
}
peek(): T {
return this.items[this.items.length - 1];
}
}
let numberStack = new Stack<number>();
numberStack.push(10);
numberStack.push(20);
numberStack.push(30);
console.log(numberStack.pop()); // 30
console.log(numberStack.peek()); // 20
console.log(numberStack.pop()); // 20
console.log(numberStack.pop()); // 10
7: Explain
Enum in TypeScript ?
Enums are a data form TypeScipt that enables us to define a set of named constants. Enums may facilitate recording purposes or setting up a number of different cases. It is a collection of related values, numeric or string values.
enum Size {
Big,
Medium
Small
}
console.log(Size.Medium); // Output: 1
//We can also access an enum value by it's number value.
console.log(Size[1]); // Output: Medium
8: What is
tsconfig.json file ?
The file tsconfig.json is a JSON-based format. We may define multiple options to display the compiler how to create the current project in the tsconfig.json file. The presence of the file tsconfig.json in a directory indicates that the folder is the root of the project TypeScript. The sample tsconfig.json is described below.
{
"compilerOptions": {
"declaration": true,
"emitDecoratorMetadata": false,
"experimentalDecorators": false,
"module": "none",
"moduleResolution": "node"
"removeComments": true,
"sourceMap": true
},
"files": [
"main.ts",
"othermodule.ts"
]
}
9: What is
Lambda/Arrow function ?
ES6
TypeScript version provides a shorthand syntax, i.e. for function expressions,
to define the anonymous function. The functions of this arrow are known as
Lambda functions. A lambda function is a function without a name. The function
arrow omits the keyword function.
let sum = (a: number, b: number): number => {
return a + b;
}
console.log(sum(10, 20)); //returns 30
We =
> operator means arrow / Lambda operator in the example as mentioned
previously. The parameters a and b here are, and the function body (a + b) is
considered.
10: Does
TypeScript supports function overloading ?
Yes,
TypeScript support function overloading. However, the execution is strange.
Only one function with multiple signatures can be implemented when we perform
overload in TypeScript.
//Function with string type parameter
function add(a:string, b:string): string;
//Function with number type parameter
function add(a:number, b:number): number;
//Function Definition
function add(a: any, b:any): any {
return a + b;
}
The
first two lines are the overload declaration function in this example. It is
overloaded by two. The former has a string parameter while the former has a
type number parameter. The third function contains the actual execution and has
a type parameter. Any type of data can take data of any kind. The execution
then checks the parameter type and executes another code based on the supplier
parameter type.
11: What
are the interfaces in Typescript ?
The interface defines the syntax for any variable or entity. Interfaces define properties, methods, and events. Only the members are declared here. Interfaces are useful in defining different members and help to define the structure of the drifting classes. Interfaces can be declared using the keyword of the interface.
interface Employee {
name: string,
dob: date,
address: string,
getDepartment: ()=>string
}
12: What
can we convert string to number using Typescript?
// Using parseInt
parseInt(x)
// Using parseFloat
parseFloat(x)
// Using Unary like +,* operator
let a = "1";
let b: number = +a;
// Using Number
Number('123')
13: What is
a '.map' file, and why/how can you use it ?
A map file is a source map file that can be used for debugging. It can be generated by setting the option of the sourceMap compiler to true in tsconfig.json
{
"compilerOptions": {
...
"sourceMap": true,
}
}
14: What
does the 'Record' type do?
It allows you to create a typed "map".
let Employee : Record<string, number> = {};
Employee.age = 35;
15: Can you
explain what are Rest parameters and its rules to declare Rest parameters?
A rest
parameter is used to pass a function to zero or more values. By prefixing the
three-dot characters ('...') before the parameter, it is declared. It makes it
possible for functions to have a variable number of arguments without using the
object argument. Where we have an undetermined number of parameters, it is very
useful.
Rules
to follow in rest parameter:
·
Only one rest parameter is allowed in a function.
·
It must be an array type.
·
It must be a last parameter in the parameter list.
function sum(a: number, ...b: number[]): number {
let result = a;
for (var i = 0; i < b.length; i++) {
result += b[i];
}
console.log(result);
}
let result1 = sum(1, 2);
let result2 = sum(1,2,4,6);
16: Explain
how we can use a class outside a module where it was defined?
Here is an example how we can use class outside module with export keyword :
module Admin {
// use the export keyword in TypeScript to access the class outside
export class Employee {
constructor(name: string, email: string) { }
}
let alex = new Employee('alex', 'alex@gmail.com');
}
// The Admin variable will allow to accessed the Employee class outside the module with the help of export keyword in TypeScript
let nick = new Admin.Employee('nick', 'nick@yahoo.com');
17: What is
"as" syntax used in TypeScript?
The
"as" is used for Type assertion in TypeScript. The as-syntax was
implemented because the original syntax (type>) clashed with JSX.
18: What
exactly is contextual typing?
If you have types on one side of the equation but not the other, the TypeScript compiler will find out the form. For instance, we can rewrite the preceding example function as follows:
let sum: (firstNumber: number, secondNumber: number) => number =
function(x, y) { return x + y; };
We
should omit the typings on the right side of the equal since TypeScript can
work it out automatically. This decreases the amount of work needed to keep our
code typed.
19: What
exactly is JSX? Is it possible to use JSX in TypeScript?
JSX is
an XML-like syntax that can be embedded. It is supposed to be translated into
valid JavaScript.
With
the React system, JSX gained popularity. TypeScript allows you to embed, type search,
and compile JSX directly into JavaScript.
To use
JSX in our file, we must name it with .tsx extension and allow the jsx feature.
20: What
JSX modes does TypeScript support?
There
are three JSX modes included with TypeScript: preserve, respond, and
react-native.
·
Preserve mode : The preserve mode holds the JSX as part of the output, ready to
be consumed by a subsequent transform stage (e.g. Babel). The output would also
have an extension of the.jsx format.
·
React mode : The react mode will emit React.createElement, which does not
need any JSX transformation before use and has a.js file extension.
·
React-native mode : The react-native mode is similar to preserve
mode in that it holds all JSX but outputs a.js file.
No comments:
Post a Comment