Typescript Flashcards

1
Q

How do you run TypeScript compiler on files?

A

tsc app.js

If we have setup a tsconfig.json, we can type tsc.
It will look for ts.config.json even if we are not in the same directory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are TypeScript Project files?

A
  • Simple JSON text file named tsconfig.json
  • Stores compiler options used with the project
  • Specifies files to be included or excluded in compilation (In a large you can use many different project files, each specifying different compiler options for each subset of projects)
  • Support configuration inheritance
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Explain basic compiler options for :

{
“compilerOptions”: {
“target”: “ES5”,
“noUnusedLocals”: true,
“outFile”: “output.js”
},
“files”: [“app/app.ts”]
}

A

{
“compilerOptions”: {
“target”: “ES5”, // tells the compiler to which version of javascript to output
“noUnusedLocals”: true, // will generate an error if I have unused local variables
“outFile”: “output.js” // name of the js file, that I want to output
},
“files”: [“app/app.ts”] // array of files I want to include in the compilation
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you initialize TypeScript Config

A

tsc –init

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you assert TypeScript, that you know that a certain object will not come as a null?

A

By adding ! (non-null assertion operator)

messagesElement!.innerText = Welcome to MultiMath! Starting a new game...;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you apply Configuration Inheritance in TypeScript?

A

1) The configuration in the root folder should be renamed to tsconfig.base.json
2) We should add an inherited configuration in the fodler of our choosing tsconfig.json
3) Ts config, as one of the properties should have the “extends” keyword:
{
“extends”: “../tsconfig.base”,
“compilerOptions”: { // all of additional keywords will be run apart of the tsconfig.base
“removeComments”: true
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the glob and how it can be used?

A

Glob is used to specify which files should be compiled. Contrary to “files” key, which requires you to match specifically which files you would like to include in the compilation, glob allows you to specify a file name pattern.

We add globs using the “include” keyword.

{
“extends”: “../tsconfig.base”,
“compilerOptions”: {
“removeComments”: true
},
“include”: [”./**/*”] // ** will tell to look recursively through all subdirectories
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the types that TypeScript Supports?

A
  • boolean
  • number (floating point value)
  • string
  • Array (string[] or Array)
  • Enum (In computer programming, an enumerated type is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language.)
  • void (Void is a data type used to represent the absence of a type, used for functions that do not return anything)
  • null
  • undefined
  • never (assigned to values that will never occur)
  • any (opt out of checking by the compiler)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are Type Annotations?

A

Type annotations are part of variable declarations that allow you to specify what data type may be assigned to a variable.

You can assign a type annotation by adding a colon to the variable declaration, like:

let x: string = “Test”;

If you do not add the type annotation, TypeScript will assign the type based on the variable declaration

let x = “Test”;

so x in this case will also always be a string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are union types in TypeScript?

A

A union type describes a value that can be one of several types.

With vertical bar ( | ) we might separate each type, number | string | boolean is the type of a value that can be a number, a string, or a boolean

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is –strictNullChecks

A

By default, null and undefined can be assigned to any type.

With –strictNullChecks, it can be avoided in TS. With that option set to true, null and undefined ae no longer valid values for every other type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are Type assertions and why are they useful in TypeScript?

A

Sometimes you’ll end up in a situation where you’ll know more about a value than TypeScript does. Usually, this will happen when you know the type of some entity could be more specific than its current type.

A type assertion is like a type cast in other languages, but it performs no special checking or restructuring of data.

Type assertions have two forms.

One is the as-syntax:
let someValue: unknown = “this is a string”;
let strLength: number = (someValue as string).length;

The other version is the “angle-bracket” syntax:
let someValue: unknown = “this is a string”;
let strLength: number = (someValue).length;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you add annotations to functions?

A

function funfunc(score: number, message?: string): string {}

? flags the parameter as optional
the last annotation is used to specify the return type of the function

We can additionally, add a default value for a parameter with “=”. This will make the parameter optional by default.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does –noImplicitAny compiler option do?

A

It will require us to pass a type annotation for all variables. It will not implicitly assign any type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the TypeScript syntax for creating arrow functions?

A

Parameters, we need to wrap parameters with (), if there are 0 or more parameters. Additionally, we need to do that, if there is type annotation to a single parameter.

We also can pass the return value from an arrow function.

const logMessage = (message: string): void => console.log(message);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How can you take advantage of TypeScript function types?

A

Whenever we hover over a function name, there will be a little popup that shows the function type.

If two functions have the same function type, we can assign either of the functions to that variable

To give a variable a function type, after colon, we need to put the expected function parameters and their types in parentheses

let logger: (value: string) => void;

17
Q

What are TypeScript Interfaces?

A

Interfaces and classes can both be used to create custom types in TypeScript.

Interfaces are a development time tool -> they are used by the compiler to type check your code, but don’t compile down to anything in JS.

  • Used to define new types
  • Have properties (define signatures of properties; it has only a name and a type)
  • Define methods (signatures; define number and types of the parameters it expects as well as method’s return type)
  • Can’t be instantiated
  • Do not provide any implementation details
18
Q

What are TypeScript Classes?

A
  • Used to define new types
  • Have properties (but can also include implementation details for the property)
  • Define methods (class methods include full method implementations, each instance of a class will get the same code for a given method)
  • Can be instantiated
19
Q

How can you create an Interface?

A

An interface is created using the “interface” keyword.

interface Employee {
name: string;
title: string;
}

extends keyword, can extend an interface

interface Manager extends Employee {
department: string;
numOfEmployees: number;
scheduleMeeting: (topic: string) => void;
}

20
Q

How can you create Classes?

A

Classes provide:
- Method implemenations
- Property implementations
- Accessors (getters and setters)
- Access modifiers:
- Public
- Private (members not accessible outside of the class)
- Protected (can only be accsessible inside of the class or any class that inherits from the class)

21
Q

What do extends and implements keywords do?

A

class WebDeveloper extends Developer {}
- Creates a very typical object-oriented inheritance relationship between the two classes.

A common practice is to write classes that implement interfaces.

class Engineer implements Employees {}

once you declared that a class will implement an interface, you’re required to provide an implementation for all of the required properties and methods.

22
Q

How can you use triple slash directives to configure a Project’s compiler

A

in the tsconfig.json,

we want to specify the entry point to a file:
“files” :[
“./app.ts”
]

then in app.ts we would like to use the triple slash directives. In vscode there is a code snippet after typing “ref”

///

by specifying this ref we provide instructions to the compiler, where to look for a file that includes some class or an interface.

23
Q

What are static members of a class?

A

They are members that you access on the class directly, not on instances of the class.

class WebDeveloper extends Developer {
static jobDescription: string = “Build cool things!”;
static logFavoriteProtocol () {

}
}

WebDeveloper.logFavoriteProtocol()

24
Q

What are constructors?

A

Constructors are a special type of function that’s executed when new instances of the class is created.

They’re a handy place for you to perform any special initialization or setup that needs to be performed for new instances of a class.

class Developer {
constructor() {
}
}

25
Q

What’s the main difference between relative references and non-relative references?

A

In general, you should use relative references when referring to your own modules and non-relative references when referring to third-party modules.

26
Q

What are Type Declaration Files

A

Type Definition Files or Type Libraries

  • TypeScript wrapper for JavaScript libraries
  • Types for variables function, etc.
  • Define valid property names
  • Define function parameters
  • Development time tool to assist the compiler and find the problems at compile time
  • Filenames end with .d.ts
27
Q

Where can I find Type Declaration files?

A
  • Find it included in the javascript library that you want to use
  • DefinitelyTyped repository
  • Nowadays it is included and can be installed with npm
    • Packages installed from @types/
28
Q

What’s the issue in JavaScript compared to TypeScript.

A

The only way in pure JavaScript to tell what fn does with a particular
value is to call it and see what happens. This kind of behavior makes it hard to predict what code
will do before it runs, which means it’s harder to know what your code is going to do while you’re
writing it. JavaScript only truly provides dynamic typing - running the code to see what happens.

The alternative is to use a static type system to make predictions about what code is expected
before it runs.

29
Q

What is union narrowing in TypeScript?

A

Narrowing occurs when we deal with union of type annotations. Sometimes a property that comes as an argument to a function can be type number | string.

Narrowing occurs when TypeScript can deduce a more specific type for a value based on the structure of the code.

function printId(id: number | string) {
if (typeof id === “string”) {
// In this branch, id is of type ‘string’
console.log(id.toUpperCase());
} else {
// Here, id is of type ‘number’
console.log(id);
}
}

30
Q

What is the difference between Type Aliases and Interfaces?

A

Type aliases and interfaces are very similar, and in many cases you can choose between them freely.
Almost all features of an interface are available in type , the key distinction is that a type
cannot be re-opened to add new properties vs an interface which is always extendable.

type Window = {
title: string
}
type Window = {
ts: TypeScriptAPI
}
// Error: Duplicate identifier ‘Window’

while the following snippet will work:

interface Window {
title: string
}
interface Window {
ts: TypeScriptAPI
}

31
Q

What are type guards?

A

Type guards are operations that checks the value returned by typeof and compares it to a string of our choosing

function printAll(strs: string | string[] | null) {
if (typeof strs === “object”) {
for (const s of strs) {
Object is possibly ‘null’.
console.log(s);
}
} else if (typeof strs === “string”) {
console.log(strs);
} else {
// do nothing
}
}

32
Q

What can in operator do when it comes to narrowing?

A

Javascript has an operator for determining if an object has a property with a name: the in
operator. TypeScript takes this into account as a way to narrow down potential types.

type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if (“swim” in animal) {
return animal.swim();
}
return animal.fly();
}

33
Q

How do you bootstrap your create react app with typescript?

A

npx create-react-app name-of-app –template typescript

34
Q

What is an unkown?

A

Unkown is a type similar to any, but you have to cast it before you use it.

We can call it a typesafe any