Typescript Flashcards

1
Q

What is Typescript

A

It’s a super set of Javascript. Typescript is transpiled to Javascript, the version of Javascript (ES version) is according to the tsconfig configuration. Typescript enhances Javascript with static type checking and some class features such as abstract classes and the public, private, protected and abstract modifiers.

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

What is a superset of a language

A

It means that all the code of the language it is a superset of is valid in the superset, but it adds more features

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

What is static type checking

A

Typescript allows a developer to annotate the types that are expected for variables and for values returned by functions, methods in classes etc. It gives linting errors when variables are used in ways that are not valid. For example string has a length property, but null doesn’t.

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

How do you install Typescript

A

npm i –save-dev typescript, then npx tsc is available.

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

How do you configure typescript

A

The tsconfig file in root of project

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

How to compile typescript

A

tsc filename.ts

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

What do you call the set types

A

Type annotations

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

Example types

A

For primitives:

The same as the Javascript built-in constructors such as String, Number, Boolean, but lower-cased. Also null or undefined.

Tupels
Arrays as generics or not
Type aliases
Interfaces
Union types
Literal types
Intersection types
null
undefined
unknown
any
never
object - bad practice
void

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

What is type inference?

A

Typescript an infer types by the values assigned OR the return of a function.

With primitives, Typescript can figure out if a variable is a string, number, boolean, undefined or null, based on what is assigned to it.

With function return values as well as arguments with default values, inference can also occur:

function someFunc(num=10){
return 10*2
}

Typescript can even infer an object type and an array type

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

Explain any type

A

If you set a variable to ‘any’ then it can be of any value.

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

When can a type implicitly be any

A

With delayed initialization, where a variable is not assigned a value or annotated with type annotation, for example:

let someVariable;

Also function argument/parameter without annotation without default value

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

How to annotate function args/params, and return values without inference

A

function(num:number):string{
return num.toString();
}

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

Return value annotations explained

A

Best to not infer only, but rather annotate. Reason, function could be long, and it just makes it easy to see what it should be. Also, linting is improved, also where the function in invoked.

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

Union type example

A

string|number

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

What is void

A

When a function returns nothing OR nullish (null/undefined) a type annotation of void is valid.

If there is no ‘return’ statement then it will have a value of undefined as the return value

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

Explain anonymous function contextual typing

A

Inference can take place because of the context of where it’s called

[‘green’,’red’,’blue’].map(color=>{})

Typescript knows that color is a string

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

Quirky behaviour on excess object properties

A

When a type is defined for an object as a function argument, passing in excess properties inline will result in linting error.

However if assigned to a variable and then passed in it’s fine.

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

Two ways of annotating object properties

A

As an interface or as a type alias

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

What is a type alias

A

A type that can be used similar to a variable in that it can be assigned in multiple places

Example:

type SomeType = string;

type Person ={
name:string;
age:number;
}

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

Convention for type alias and interface names

A

Make it PascalCase

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

Explain optional types

A

Use ? in front of :

type Person={
name?:string;
}

This means that name can be string OR undefined

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

Readonly modifier

A

Ensure that an object property value cannot be overwritten, only read

type User = {
readonly id: string;
}

OR

interface User {
readonly id:string;
}

const user:User = {
id:’234234’
}

user.id=’3333’ // results in error

class UserObj implements User {
//cannot be updated within class, or outside of class
readonly id:string;
}

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

Example intersection type

A

type User={
id:string;
}

type Profile={
name:string;
}

type UserProfile=User&Profile

results in

{
id:string;
name:string;
}

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

Example array types - both syntaxes

A

const numbers:number[]=[1,2,3]
const numbers : Array<string></string>

type User ={name:string}
const users:User[] = [{name:’Albert’}]

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

What are literal types

A

Exact values assigned to type for example:
const names : ‘albert’|’lucas’

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

Multi-dimensional array example

A

const something:string[][]=[
[‘a’,’b’],
[‘c’,’d’,’e’]
]

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

What is type narrowing

A

It’s the way that Typescript is able to narrow a type in a certain code-block to a certain type based on if statements that check the types in some way.

28
Q

Syntax for union type with arrays

A

const someVar:(number|string)[]=[1,’1’]

29
Q

Explain primitive types

A

Same as builtin javascript constructors like new Boolean(), new String(), new Number()

boolean, string, number

Also undefined and null

That is, not objects or arrays.

30
Q

What is a tupel

A

It’s a type that annotates array index values, with an array of a fixed length

const someValue :[number,string]= [5,’whatever’]

31
Q

Tupel quirky behaviour

A

You can push extra elements onto an array, and Typescript won’t complain about it. Same with popping.

32
Q

Explain enums

A

Set of named constants. Values can be numbers or strings.

For example:

enum SomeEnum {
YES=’yes’,
NO=’no’
}

enum SomeEnum {
YES=0,
NO=1,
}

Use it as SomeEnum.yes or SomeEnum.no

If values not given per constant, it defaults to 0-based index values like an array

If first item is set to for example 9 then the following items increment from there.

33
Q

Purpose of interface

A

You can define the shape of an object, like an object literal, like type aliases.

However a class is meant to implement an interface. Then the class needs to implement the properties and the methods as defined in the interface.

An interface is what the client can interface with, when implemented on a class. This is why all properties and methods can only be public (publically accessible by the client)

34
Q

Example of an interface

A

interface User {
readonly id:string;
sayName(someVar:string):string;
saySurname:()=>string;
surname?:string;
age?:20;
}

35
Q

Reopening interfaces

A

Interfaces are combined if two of them have the same name in the same context.

interface Dog {
name:string;
}

interface Dog {
bark():string;
}

Dog is NOW

interface Dog{
name:string;
bark():string;
}

36
Q

Which modifiers are allowed on an interface?

A

Only readonly.

If the encapsulation modifiers are not set, then it defaults to public.

An interface can be seen as a contract, and you can specify which methods and properties should be available from outside the class (the client).

It sets what the client has available when interfacing with the class.

37
Q

What is the difference between a class and an object

A

An object is an instance of a class.
A class is a blueprint of the object.

38
Q

Explain super

A

It’s important to invoke super() in the constructor of the child class, even if the parent class doesn’t need values to be sent to it from the child via super()

super() allows a child class to send data up to the parent class’ constructor.

39
Q

How do you create private properties and methods in Javascript (ES6)

A

Type the octothorp (#) just before properties and methods that are meant to be private

40
Q

What is an abstract class - not available in Javascript, just Typescript

A

Use the abstract keyword before the class keyword. An abstract class cannot be instantiated. Would usually be used in tandem with static methods, if the class only contains static methods.

Another use case is for abstractions, where a child class must implement all abstract properties and methods in an abstract parent class.

41
Q

Explain accessors

A

Object accessors are getters and setters.

It makes it possible to update an object’s private properties and to retrieve them without making them public.

It makes it possible for the creator of the class to enforce encapsulation and to only expose what is neccessary and it makes it possible to define an interface that the class exposes for manipulation from outside.

42
Q

Getters and setters syntax

A

For the same property/properties, create a get something(), set something() method.

In the setter, update a value. In the getter return the value.

Now from outside you can

const car = new Car();
car.model=’ford’; // calls setter
console.log(card.model) //calls getter

43
Q

Explain inheritance

A

One class can inherit, via the extends keyword, public/protected properties and methods from a parent class.

Interfaces can also inherit from each other.

Javascript doesn’t support protected properties and methods, but Typescript does.

44
Q

Explain static methods and properties

A

You can access public static methods without a class instance.

Validation.isEmail(). Validation is the class.

45
Q

What is parameter properties shorthand?

A

Short hand for setting properties via constructor

constructor(public name:string, private surname:string){}

46
Q

What are the public, private and protected keywords called?

A

Modifiers

47
Q

What is the readonly keyword called

A

Modifier

48
Q

Explain unkown type

A

It’s similar to any BUT, it’s more restrictive.

Typescript expects you to do type-narrowing to prevent linting errors.

49
Q

What is type narrowing

A

It is Typescript’s ability to determine what a type assigned to a variable would be in a given context, based on guards (if statements)

50
Q

Type narrowing examples

A

These if statements are called guards

Typeof guards - if statements for primitives

equality narrowing - === OR == if statements

truthiness guards - narrowing out null/undefined with if statements

The in operator : ‘name’ in user (user is object) class or literal

Instanceof operator - checking if object is an instance of a given class: myVar instanceof User for example

Type predicates

51
Q

Explain type predicates

A

A reusable function to determine whether a variable is of a certain type and enforce type narrowing with the ‘is’ keyword.

Syntax:

const isCat = function(animal:Cat|Dog) animal is Cat {
// logic to check it this is a CAT, and return true or false
}

52
Q

Explain generic functions

A

It allows the developer to create a function, stating that the type can be anything, or of a certain type (type constraint - using extends wit type alias or interface), and when the function is invoked, the type can be specified.

Typescript is also to infer types based on the args given if the generic function has been created.

Works for args and return type

You can also set a default if the type is not given when invoked.

53
Q

Quirk with tsx file and generic

A

When it’s an arrow function, add a comma after the generic for example <T,> so that Typescript knows it’s not JSX

54
Q

Generic naming convention

A

start at T, next U, V etc

55
Q

How to set default type for generic type parameters

A

<T = number> for example

56
Q

How do you add generic parameters to class

A

Add generic type after class name and use it within class

class MyClass<T=number>{
something:T;
}

57
Q

What are type assertions

A

You can tell Typescript that a variable is of a certain type.

Basically changing it from one type to another.

Example:
`
const myVar:unknown = 10;

const secondVar = myVar as number;

// secondVar is now a number

`

58
Q

non-null assertion operator

A

If you know for a fact that something is not null or undefined (nullish), then you can tell Typescript by using an exclamation mark post-fix.

const btn = document.getElementById(‘btn’)!;

OR

const btn = document.getElementById(‘btn’);

btn!.addEventListener() ….

59
Q

What are utility types

A

Think of them as functions that can manipulate existing types in order to make new types. Examples would be Pick<> to only pick the properties you’d like.

`
type User{
name:string;
age:number;
password:string;
}

type OtherType = Pick<User,’name’|’age’>
`

60
Q

How to annotate an object with dynamic properties

A

type SomeType={
[key:string]:number,
}

61
Q

Example using enums as object properties

A

enum SomeEnum {
ACTIVE=’active’,
INACTIVE=’inactive’,
}

const someObject = {
[SomeEnum.ACTIVE]:true,
[SomeEnum.INACTIVE]:false,
}

62
Q

If an access modifiers is not given for a class method or a property, what is the default?

A

Public

63
Q

Explain public, private and protected methods and properties

A

Public, can be accessed outside of the class via dot notation

Private, can only be accessed within the class via dot notation

Protected, a parent class’ protected properties and methods can be accessed by the parent and the children classes that inherit from the parent class.

64
Q

ES6 getters and setters

A
65
Q

Dynamically create type based on object shape

A