TypeScript is an open source superset of JavaScript developed by Microsoft for adding additional functionality without breaking existing programs.

Because of its unique advantages, such as static typing and many shorthand notations, TypeScript is now widely used by front-end and full-stack developers on large projects.

1. What are TypeScript’s key features?

  • Cross-platform: the TypeScript compiler can be installed onAny operating systemOn Windows, macOS, and Linux.
  • ES6 features: TypeScript includes most of the planned ECMAScript 2015 (ES6) features, such as arrow functions.
  • Object-oriented language: TypeScript provides all standard OOP functionality, such as classes, interfaces, and modules.
  • Static type checking: TypeScript uses static typing and helps with type checking at compile time. As a result, you can find compile-time errors while writing code without having to run scripts.
  • Optional static typing: If you’re used to dynamic typing in JavaScript, TypeScript also allows optional static typing.
  • DOM manipulation: You can manipulate the DOM using TypeScript to add or remove client-side web page elements.

2. What are the benefits of using TypeScript?

  • TypeScript is more expressive, which means its syntax is less cluttered.
  • Because advanced debuggers focus on catching logic errors before compile time, debugging is easy.
  • Static typing makes TypeScript easier to read and more structured than JavaScript’s dynamic typing.
  • Due to generic translation, it can be used cross-platform, both in client and server projects.

What are TypeScript’s built-in data types?

  • Numeric type: A value used to represent a numeric type. All numbers in TypeScript are stored as floating point values.
const m:number = value
Copy the code
  • Boolean type: A logical binary switch containing true or false
const m:bool = Boolean value
Copy the code
  • Null type: Null denotes a variable whose value is undefined.
const m:string = ""
Copy the code
  • Undefined type: An undefined literal that is the starting point for all variables.
const m:string = null
Copy the code
  • Void type: Type assigned to a method that does not return a value.
const m:void = undefined
Copy the code

What is the current stable version of TypeScript?

The current stable release is 4.2.3.

What are interfaces in TypeScript?

An interface defines a contract or structure for an object that uses the interface. An interface is a keyword-defined interface that can contain property and method declarations using functions or arrow functions.

interface IEmployee {
    empCode: number
    empName: string
    getSalary: (number) => number // arrow function
    getManagerName(number): string
}
Copy the code

What are modules in TypeScript?

Modules in TypeScript are collections of related variables, functions, classes, and interfaces. You can think of a module as a container that contains everything you need to perform a task. Modules can be imported to easily share code between projects.

module fn{
    class onFn{
        export sum(x, y){
            return x + y
        }
    }
}
Copy the code

7. How does the backend use TypeScript?

You can combine Node.js with TypeScript to bring the benefits of TypeScript to your back-end work. Simply type the following command to install the TypeScript compiler into your Node.js:

NPM i-g typescript // or yarn add typescript -gCopy the code

What are type assertions in TypeScript?

Type assertions in TypeScript work like type conversions in other languages, but without the type checking or data reorganization that is possible in languages like C# and Java. Type assertions have no impact on the runtime and are used only by the compiler. Type assertion is essentially a soft version of type conversion that advises the compiler to treat a variable as a certain type, but does not force it into the model if it is in a different form.

How do I create variables in TypeScript?

You can create variables in three ways: var, let, and const.

  • Var is the old style of strictly scoped variables. You should avoid using VAR whenever possible because it can cause problems in larger projects.
var m:number = 1
Copy the code
  • Let is the default way to declare variables in TypeScript. Compared to VAR, let reduces the number of compile-time errors and improves the readability of code.
let m:number = 1
Copy the code
  • Const creates a constant variable whose value cannot be changed. It uses the same scope rules, lets, and helps reduce the overall complexity of the program.
const m:number = 100
Copy the code

How do I call a base-class constructor from a subclass in TypeScript?

You can use the super() function to call the base class constructor.

class Animal { name: string; constructor(name: string) { this.name = name } move(distanceInMeters: number = 0) { console.log(`${this.name} moved ${distanceInMeters}m.`) } } class Snake extends Animal { constructor(name:  string) { super(name) } move(distanceInMeters = 5) { console.log("Slithering..." ) super.move(distanceInMeters) } }Copy the code

Explain how to use TypeScript mixin.

Mixins are essentially an inheritance that works in the opposite direction. Mixins allow you to build new classes by combining simpler partial class Settings from previous classes. Instead, class A inherits its functionality from class B, and class B needs to return additional functionality from A new class.

How do you check null and undefined in TypeScript?

You can use juggle-check, which checks for null and undefined, or strict-check, which returns values where true is set to null and does not evaluate variables that are not defined by true.

//juggle
if (x == null) {
    //
}
// --------------------
var a: number
var b: number = null
function strictCheck(x, name) {
    if (x == null) console.log(name + ' == null')
    if (x === null) console.log(name + ' === null')
    if (typeof x === 'undefined') console.log(name + ' is undefined')
}  
strictCheck(a, 'a')
strictCheck(b, 'b')
Copy the code

What are getters/setters in TypeScript? How do you use them?

Getters and setters are special types of methods that help you delegate different levels of access to private variables depending on the needs of your program. Getters allows you to reference a value but not edit it. Setters allow you to change the value of a variable, but do not view its current value. These are essential for implementing encapsulation. For example, a new employer may be able to know the number of employees at a GET company, but not set.

const fullNameMaxLength = 10
class Employee {
  private _fullName: string = ""
  get fullName(): string {
    return this._fullName
  }
  set fullName(newName: string) {
    if (newName && newName.length > fullNameMaxLength) {
      throw new Error("fullName has a max length of " + fullNameMaxLength)
    }
    this._fullName = newName
  }
}
let employee = new Employee()
employee.fullName = "Bob Smith"
if (employee.fullName) {
  console.log(employee.fullName)
}
Copy the code

How do I allow classes defined outside a module to be accessible?

You can use the export keyword to open the module for use outside the module.

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', '[email protected]');
}
// The Admin variable will allow you to access the Employee class outside the module with the help of the export keyword in TypeScript
let nick = new Admin.Employee('nick', '[email protected]')
Copy the code

How do I convert strings to numbers using Typescript?

Like JavaScript, you can use the parseInt or parseFloat functions to convert strings to integers or floats, respectively. You can also use the unary operator + to convert the string to the most appropriate number type, with “3” becoming an integer, 3 and “3.14” becoming floating point 3.14.

const x = "32"
const y: number = +x
Copy the code

16, What is a.map file and why/how to use it?

The.map file is the source map that shows how the original typescript code is interpreted as usable JavaScript code. They help simplify debugging because you can catch any strange compiler behavior. Debugging tools can also use these files to allow you to edit the underlying TypeScript instead of the emitted JavaScript files.

17. What are classes in TypeScript? How do you define them?

Class represents the shared behavior and properties of a set of related objects. For example, our class might be Student, all of whose objects have the attendClass method. On the other hand, John is a separate instance of Type, Student may have additional unique behaviours such as attendextracurpassionately. You declare the class with the keyword:

class Student {    
    studCode: number
    studName: string
    constructor(code: number, name: string) {    
            this.studName = name 
            this.studCode = code 
}
Copy the code

18. What’s TypeScript’s relationship to JavaScript?

TypeScript is an open source syntactic superset of JavaScript that compiles to JavaScript. All of the original JavaScript libraries and syntax are still valid, but TypeScript adds additional syntax options and compiler capabilities not found in JavaScript. TypeScript also works with most of the same technical interfaces as JavaScript, such as Angular and jQuery.

19. What is JSX in TypeScript?

JSX is an embeddable XML-like syntax that allows you to create HTML. TypeScript supports embedding, type checking, and compiling JSX directly into JavaScript.

What JSX schemas does TypeScript support?

  • TypeScript has built-in support for Preserve, React, and React-Native.
  • Preserve keeps JSX intact for subsequent conversions.
  • React is not converted by JSX. Instead, react. CreateElement is emitted and output as a.js file extension.
  • React native combines preserve, React because it maintains all JSX and output as.js extensions.

How do I compile TypeScript files?

You need to call the TypeScript compiler TSC to compile the file. You need to install the TypeScript compiler. You can use NPM.

npm install -g typescript
tsc <TypeScript File Name>
Copy the code

22. What scopes are available in TypeScript? How does this compare to JS?

  • Global scope: Defined outside of any class and can be used anywhere in the program.
  • Function/class scope: Variables defined in a function or class can be used anywhere within that scope.
  • Local scope/code block: Variables defined in a local scope can be used anywhere in the block.

23. What are arrow /lambda functions in TypeScript?

The fat arrow function is a shorthand syntax for defining function expressions for anonymous functions. It is similar to lambda functions in other languages. The arrow function lets you skip the function keyword and write cleaner code.

24. Explain REST parameters and declare rules for REST parameters.

The remaining arguments allow you to pass a different number of arguments (zero or more) to the function. This is useful when you are not sure how many arguments a function will take. All arguments after the remaining symbols… Will be stored in an array. Such as:

function Greet(greeting: string, ... names: string[]) { return greeting + " " + names.join(", ") + "!" } Greet("Hello", "Steve", "Bill"); // returns "Hello Steve, Bill!" Greet("Hello"); // returns "Hello !"Copy the code

The REST parameter must be the last parameter defined, and each function can have only one REST parameter.

25, What is the triple slash command? What are the three slash instructions?

The triple slash directive is a single-line comment that contains the XML markup used as a compiler directive. Each instruction represents what to load during compilation. The triple slash directive works only at the top of its file and will be treated as a normal comment anywhere else in the file.

/// <reference path="..." /> is the most common directive that defines dependencies between files. /// <reference types="..." /> Is similar to path but defines package dependencies. /// <reference lib="..." /> allows you to explicitly include built-in lib files.Copy the code

26. What’s the use of Omit types?

Omit is a form of the utility type that facilitates common type conversions. Omit Omit allows you to construct types by passing current types and selecting Keys to Omit in the new Type.

Omit
,>

interface Todo {
  title: string;
  description: string
  completed: boolean
  createdAt: number
}
type TodoPreview = Omit<Todo, "description">
Copy the code

27. How does TypeScript implement function overloading?

To override functions in TypeScript, you simply create two functions with the same name but different parameter/return types. Both functions must take the same number of arguments. This is an important part of polymorphism in TypeScript. For example, you can create an Add function that adds the two arguments if they are numbers and concatenates them if they are strings.

function add(a:string, b:string):string
function add(a:number, b:number): number
function add(a: any, b:any): any {
    return a + b;
}
add("Hello ", "Steve"); // returns "Hello Steve" 
add(10, 20); // returns 30
Copy the code

28. How to make all attributes of an interface optional?

You can easily make all attributes optional using partial mapping types.

29, When should I use the keyword unknown?

Unknown, if you do not know what type is expected beforehand but want to assign it later, the any keyword should be used and will not work.

30. What are decorators and what can they be applied to?

A decorator is a special declaration that allows you to modify a class or class member at once by using the @annotation tag. Each decorator must reference a function that will be evaluated at run time. For example, the decorator @sealed would correspond to sealed. Any marked @sealed will be used to evaluate the sealed function.

function sealed(target) {
  // do something with 'target' ...
}
Copy the code

They can be attached to:

  • Class declaration
  • methods
  • accessories
  • features
  • parameter

Note: Decorators are not enabled by default. To enable them, you must experimentalDecorators edit the fields in the compiler options either from the tsconfig.json file or from the command line.

The last

Public number: little he grew up, The Buddha department more article, is oneself had stepped on the pit or is learned the thing interested little friend welcome to pay attention to me oh I was: he Little Life. Everybody progress duck together