Record some TypeScript questions.
What is TypeScript and why would I use it in place of JavaScript?
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:
- TypeScript supports new ECMAScript standards and compiles them to older ECMAScript targets of your choosing. This means that you can use features of ES2015 and beyond.
- JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript.
- TypeScript adds type support to JavaScript. The type system of TypeScript is relatively rich and includes: interfaces, enums, hybrid types, generics, union and intersection types, access modifiers and much more. TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference.
- The development experience with TypeScript is a great improvement over JavaScript. The IDE is informed in real-time by the TypeScript compiler on its rich type information.
- With strict null checks enabled the TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type.
- To use TypeScript you need a build process to compile to JavaScript code. The TypeScript compiler can inline source map information in the generated .js files or create separate .map files. This makes it possible for you to set breakpoints and inspect variables during runtime directly on your TypeScript code.
- TypeScript is open source and backed by Microsoft.
TypeScript has following benefits.
- It helps in code structuring.
- Use class based object oriented programming.
- Impose coding guidelines.
- Offers type checking.
- Compile time error checking.
- Intellisense.
List the basic types in Typescript
Boolean
1
let isDone: boolean = false;
Number
1
2
3
4let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;String
1
let color: string = "blue";
Array
1
2let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];Tuple
1
2let x: [string, number];
x = ["hello", 10];Enum
1
2enum Color {Red, Green, Blue}
let c: Color = Color.Green;1
2
3enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];
console.log(colorName); // Displays 'Green' as its value is 2 aboveAny
1
2
3let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;Void
1
2
3
4
5
6function warnUser(): void {
console.log("This is my warning message");
}
let unusable: void = undefined;
unusable = null; // OK if `--strictNullChecks` is not givenNull and Undefined
1
2let u: undefined = undefined;
let n: null = null;Never
1
2
3
4
5
6
7
8
9
10
11
12
13// Function returning never must have unreachable end point
function error(message: string): never {
throw new Error(message);
}
// Inferred return type is never
function fail() {
return error("Something failed");
}
// Function returning never must have unreachable end point
function infiniteLoop(): never {
while (true) {
}
}
What are Modules in Typescript?
Modules in Typescript helps in organizing the code. There are 2 types of Modules — Internal and External.
- Internal Modules are now replaceable by using Typescript’s namespace.
- External Modules used to specify and load dependencies between multiple external js files. If there is only one js file used, then external modules are not relevant.
Explain generics in TypeScript
Generics are able to create a component or function to work over a variety of types rather than a single one.
1 | /** A class definition with a generic parameter */ |
What is Interface in TypeScript?
One of TypeScript’s core principles is that type-checking focuses on the shape that values have.
An interface is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes.
When you define your interface you’re saying that any object (not an instance of a class) given this contract must be an object containing interfaces properties.
When to use interfaces and when to use classes in TypeScript?
If you need to create an instance of perhaps a custom object, while getting the benefits of type-checking things such as arguments, return types or generics - a class makes sense.
If you’re not creating instances - we have interfaces at our disposal, and their benefit comes from not generating any source code, yet allowing us to somewhat “virtually” type-check our code.
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 initializing 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 initialization 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.