TypeScript starts from the same syntax and semantics that millions of JavaScript developers know today. Don't miss that advanced list of 36 TypeScript interview questions and answers and nail your next web developer tech interview in style.
Generics are able to create a component or function to work over a variety of types rather than a single one.
/** A class definition with a generic parameter */
class Queue<T> {
private data = [];
push = (item: T) => this.data.push(item);
pop = (): T => this.data.shift();
}
const queue = new Queue<number>();
queue.push(0);
queue.push("1"); // ERROR : cannot push a string. Only numbers allowedWe can call base class constructor using super().
TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code. For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.
In details:
--strictNullChecks compiler flag) the TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type. Typescript doesn’t only work for browser or frontend code, you can also choose to write your backend applications. For example you could choose Node.js and have some additional type safety and the other abstraction that the language brings.
npm i -g typescript{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "build"
}
}tscnode build/index.jsFor example:
T extends U ? X : YThe type above means when T is assignable to U the type is X, otherwise the type is Y.
Evaluation of a conditional type is deferred when evaluation of the condition depends on type variables in T or U, but is resolved to either X or Y when the condition depends on no type variables.
An example:
type TypeName<T> =
T extends string ? "string" :
T extends number ? "number" :
T extends boolean ? "boolean" :
T extends undefined ? "undefined" :
T extends Function ? "function" :
"object";
type T0 = TypeName<string>; // "string"
type T1 = TypeName<"a">; // "string"
type T2 = TypeName<true>; // "boolean"
type T3 = TypeName<() => void>; // "function"
type T4 = TypeName<string[]>; // "object"The answer is YES. There are 4 main principles to Object Oriented Programming:
TypeScript can implement all four of them with its smaller and cleaner syntax.
null and undefined in TypeScript?Just use:
if (value) {
}It will evaluate to true if value is not:
nullundefinedNaN''0falseTypesScript includes JavaScript rules.
enum with string values?String-based enums (TypeScript 2.4) allow us to assign string values to an enum member.
Consider:
enum E {
hello = "hello",
world = "world"
};In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with "A class member cannot have the 'const' keyword." TypeScript 2.0 has the readonly modifier:
class MyClass {
readonly myReadonlyProperty = 1;
myMethod() {
console.log(this.myReadonlyProperty);
}
}
new MyClass().myReadonlyProperty = 5; // error, readonlyAn optional chain is an optional expression followed by one or more subsequent regualr property access, element access, or call argument lists:
a?.b.c; // property access chain
a?.b[x]; // element access chain
a?.b(); // call chainWhich means:
a is either null or undefined, the rest of the chain is also not evaluated.a is any other value, the expression is evaluated as normal.In this cases, if a.b were either null or undefined, the expression would still throw as the ?. token only guards the value of a.
TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object.
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
var myBar = myFoo.bar; // correct (get)
myFoo.bar = true; // correct (set).map files are source map files that let tools map between the emitted JavaScript code and the TypeScript source files that created it. Many debuggers (e.g. Visual Studio or Chrome's dev tools) can consume these files so you can debug the TypeScript file instead of the JavaScript file.
We use classes as object factories. A class defines a blueprint of what an object should look like and act like and then implements that blueprint by initialising class properties and defining methods. Classes are present throughout all the phases of our code.
Unlike classes, an interface is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes. Once code is transpiled to its target language, it will be stripped from interfaces.
A class may define a factory or a singleton by providing initialisation to its properties and implementation to its methods, an interface is simply a structural contract that defines what the properties of an object should have as a name and as a type.
String and string in TypeScript?String is the JavaScript String type, which you could use to create new strings.string is the TypeScript string type, which you can use to type variables, parameters and return values.For example:
var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string = String("Hello World");Consider the code:
class Foo {
save(callback: Function) : void {
//Do the save
var result : number = 42; //We get a number from the save operation
//Can I at compile-time ensure the callback accepts a single parameter of type number somehow?
callback(result);
}
}
var foo = new Foo();
var callback = (result: string) : void => {
alert(result);
}
foo.save(callback);Can you make the result parameter in save a type-safe function? Rewrite the code to demonstrate.
In TypeScript you can declare your callback type like:
type NumberCallback = (n: number) => any;
class Foo {
// Equivalent
save(callback: NumberCallback): void {
console.log(1)
callback(42);
}
}
var numCallback: NumberCallback = (result: number) : void => {
console.log("numCallback: ", result.toString());
}
var foo = new Foo();
foo.save(numCallback)Yes, TypeScript does support function overloading but the implementation is a bit different if we compare it to OO languages. We are creating just one function and a number of declarations so that TypeScript doesn't give compile errors. When this code is compiled to JavaScript, the concrete function alone will be visible. As a JavaScript function can be called by passing multiple arguments, it just works.
class Foo {
myMethod(a: string);
myMethod(a: number);
myMethod(a: number, b: string);
myMethod(a: any, b?: string) {
alert(a.toString());
}
}Decorators can be used to modify the behavior of a class or become even more powerful when integrated into a framework. For instance, if your framework has methods with restricted access requirements (just for admin), it would be easy to write an @admin method decorator to deny access to non-administrative users, or an @owner decorator to only allow the owner of an object the ability to modify it.
class CRUD {
get() { }
post() { }
@admin
delete() { }
@owner
put() { }
}TypeScript is referred as optionally statically typed, which means you can ask the compiler to ignore the type of a variable. Using any data type, we can assign any type of value to the variable. TypeScript will not give any error checking during compilation.
Consider:
var unknownType: any = 4;
unknownType = "Okay, I am a string";
unknownType = false; // A boolean.Classes define in a module are available within the module. Outside the module you can’t access them.
module Vehicle {
class Car {
constructor (
public make: string,
public model: string) { }
}
var audiCar = new Car("Audi", "Q7");
}
// This won't work
var fordCar = Vehicle.Car("Ford", "Figo");As per above code, fordCar variable will give us compile time error. To make classes accessible outside module use export keyword for classes.
module Vehicle {
export class Car {
constructor (
public make: string,
public model: string) { }
}
var audiCar = new Car("Audi", "Q7");
}
// This works now
var fordCar = Vehicle.Car("Ford", "Figo");To check the type of a variable or a constant, you can use the typeof operator followed by the variable name in TypeScript.
Consider:
// a simple variable
let name = "John Doe";
// check if the "name" variable type is of "string"
if (typeof name === "string") {
console.log("It is of 'string' type");
} else {
console.log("It is not of 'string' type");
}
/* OUTPUT: */
// It is of 'string' typenever, unknown, and any in TypeScript?never in positions where there will not or should not be a value.unknown where there will be a value, but it might have any type.any unless you really need an unsafe escape hatch.Consider:
class Point {
x: number;
y: number;
}
interface Point3d extends Point {
z: number;
}
let point3d: Point3d = {x: 1, y: 2, z: 3};Yes, the code is valid. A class declaration creates two things: a type representing instances of the class and a constructor function. Because classes create types, you can use them in the same places you would be able to use interfaces.
null and undefined in TypeScript?Using a juggling-check (it is where the type is juggled), you can test both null and undefined in one hit:
if (x == null) {If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:
if (x === null) {private fields in TypeScriptPrivate fields start with a # character. Sometimes we call these private names.private field name is uniquely scoped to its containing class.public or private can't be used on private fields.Private fields can't be accessed or even detected outside of the containing class - even by JS users! Sometimes we call this hard privacy.Consider:
class Person {
#name: string;
constructor(name: string) {
this.#name = name;
}
greet() {
console.log(`Hello, my name is ${this.#name}!`);
}
}
let jeremy = new Person("Jeremy Bearimy");
jeremy.#name;
// ~~~~~
// Property '#name' is not accessible outside class 'Person'
// because it has a private identifier.There are mainly 3 components of TypeScript .
The idea behind Structural Typing is that two types are compatible if their members are compatible.
For example:
MyPoint and YourPoint, both with public int properties x and y, are not interchangeable, even though they are identical.Consider:
interface Pet {
name: string;
}
class Dog {
name: string;
}
let pet: Pet;
// OK, because of structural typing
pet = new Dog();type and interface in TypeScript?interface is a contract that the following properties should be there in an object. interface is not class. It is used when language does not support Multiple Inheritance. So interface can be a common structure between different classes.
Interfaces can be extended:
interface A {
x: number;
}
interface B extends A {
y: string;
}Interfaces can also be augmented
interface C {
m: boolean;
}
// ... later ...
interface C {
n: number;
}Type is like a variable declaration which holds the information of typeof other variable. type is like a superset of interfaces, classes, function signature, other types or even values (like type mood = 'Good' | 'Bad'). At the end type describes the possible structure or value of a variable:
type NumOrStr = number | string;
type NeatAndCool = Neat & Cool;
type JustSomeOtherName = SomeType;So in general if you just have a plain object type, as shown in your question, an interface is usually a better approach. If you find yourself wanting to write something that can't be written as an interface, or want to just give something a different name, a type alias is better.
?.) and Non-null assertion operator (!) in TypeScript?Non-null assertion operator:
null.null, then your code will crash.Optional chaining:
null or undefined.null or undefined, then TypeScript will simply stop executing the property chain further and your code will proceed.?. is safer to use than non-null assertions !.a?.b.c, if a.b is null, then a.b.c will evaluate to undefined, right?unknown and any type?declare keyword in TypeScriptRust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...
Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...
Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...