Typescript Flashcards
What is Typescript
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.
What is a superset of a language
It means that all the code of the language it is a superset of is valid in the superset, but it adds more features
What is static type checking
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 do you install Typescript
npm i –save-dev typescript, then npx tsc is available.
How do you configure typescript
The tsconfig file in root of project
How to compile typescript
tsc filename.ts
What do you call the set types
Type annotations
Example types
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
What is type inference?
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
Explain any type
If you set a variable to ‘any’ then it can be of any value.
When can a type implicitly be any
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 to annotate function args/params, and return values without inference
function(num:number):string{
return num.toString();
}
Return value annotations explained
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.
Union type example
string|number
What is void
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
Explain anonymous function contextual typing
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
Quirky behaviour on excess object properties
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.
Two ways of annotating object properties
As an interface or as a type alias
What is a type alias
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;
}
Convention for type alias and interface names
Make it PascalCase
Explain optional types
Use ? in front of :
type Person={
name?:string;
}
This means that name can be string OR undefined
Readonly modifier
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;
}
Example intersection type
type User={
id:string;
}
type Profile={
name:string;
}
type UserProfile=User&Profile
results in
{
id:string;
name:string;
}
Example array types - both syntaxes
const numbers:number[]=[1,2,3]
const numbers : Array<string></string>
type User ={name:string}
const users:User[] = [{name:’Albert’}]
What are literal types
Exact values assigned to type for example:
const names : ‘albert’|’lucas’
Multi-dimensional array example
const something:string[][]=[
[‘a’,’b’],
[‘c’,’d’,’e’]
]
What is type narrowing
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.
Syntax for union type with arrays
const someVar:(number|string)[]=[1,’1’]
Explain primitive types
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.
What is a tupel
It’s a type that annotates array index values, with an array of a fixed length
const someValue :[number,string]= [5,’whatever’]
Tupel quirky behaviour
You can push extra elements onto an array, and Typescript won’t complain about it. Same with popping.
Explain enums
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.
Purpose of interface
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)
Example of an interface
interface User {
readonly id:string;
sayName(someVar:string):string;
saySurname:()=>string;
surname?:string;
age?:20;
}
Reopening interfaces
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;
}
Which modifiers are allowed on an interface?
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.
What is the difference between a class and an object
An object is an instance of a class.
A class is a blueprint of the object.
Explain super
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.
How do you create private properties and methods in Javascript (ES6)
Type the octothorp (#) just before properties and methods that are meant to be private
What is an abstract class - not available in Javascript, just Typescript
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.
Explain accessors
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.
Getters and setters syntax
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
Explain inheritance
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.
Explain static methods and properties
You can access public static methods without a class instance.
Validation.isEmail(). Validation is the class.
What is parameter properties shorthand?
Short hand for setting properties via constructor
constructor(public name:string, private surname:string){}
What are the public, private and protected keywords called?
Modifiers
What is the readonly keyword called
Modifier
Explain unkown type
It’s similar to any BUT, it’s more restrictive.
Typescript expects you to do type-narrowing to prevent linting errors.
What is type narrowing
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)
Type narrowing examples
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
Explain type predicates
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
}
Explain generic functions
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.
Quirk with tsx file and generic
When it’s an arrow function, add a comma after the generic for example <T,> so that Typescript knows it’s not JSX
Generic naming convention
start at T, next U, V etc
How to set default type for generic type parameters
<T = number> for example
How do you add generic parameters to class
Add generic type after class name and use it within class
class MyClass<T=number>{
something:T;
}
What are type assertions
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
`
non-null assertion operator
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() ….
What are utility types
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’>
`
How to annotate an object with dynamic properties
type SomeType={
[key:string]:number,
}
Example using enums as object properties
enum SomeEnum {
ACTIVE=’active’,
INACTIVE=’inactive’,
}
const someObject = {
[SomeEnum.ACTIVE]:true,
[SomeEnum.INACTIVE]:false,
}
If an access modifiers is not given for a class method or a property, what is the default?
Public
Explain public, private and protected methods and properties
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.
ES6 getters and setters
Dynamically create type based on object shape