The Basics Flashcards
Using template literals, how do you output to console hello math if math is stored in a name const?
const name = math; console.log(`Hello ${name}`);
Write a fully typed function called add that takes 2 parameters a and b and return the result of a + b
function add(a: number, b: number): number { return a + b; }
Using the arrow function notation write a fully typed function called add that takes 2 parameters a and b and return the result of a + b. The function has to be specific to the number type.
const add = (a: number, b: number): number => a + b;
Can a function be assigned to a const ?
Yes. For example:
const add = function (a: number, b: number): number {
return a + b;
};
Are function parameters required by default in Typescript ?
Yes. For instance, calling :
function add(a: number, b: number) { return a + b; } With : add(3) // a single parameter we are missing b... //Will raise an error.
How can we make a parameter optional in Typescript?
By adding ? after the parameter. For example:
function doSomething(a: number, b?: number): number { //logic. We need to handle the fact that b might or might not be provided... }
What is the value of an optional parameter in Typescript when it’s not provided?
undefined
What is the nullish coalescing operator ?
??
What happens to Typescript types at runtime?
They don’t exist…
In Typescript what will be the type of:
let today = new Date(2023-01-01);
The type will be Date. This is a Typescript specific type that doesn’t exist in Javascript. In Javascript the type of today would be object.
What is the type of name in:
const name = “math”;
The type will be ‘math’ because Ts infers that this is a string constant… There is only one possible value and this is called a string literal type.
What is the type days in:
const days = 31;
31 a number literal
What is the type of today in:
~~~
const today = new Date(2023-01-01);
~~~
The type is Date a Typescript specific type.
What will be the type of nameAgain in:
~~~
const name = “math”;
const nameAgain = last;
~~~
The type will be ‘math’ a string literal.
What will be the type of nameAgain in:
~~~
const name = “math”;
let nameAgain = last;
~~~
The type will be ‘math’ a string literal.
What will be the type of ourName in :
~~~
const myName = “math”;
const yourName = “samantha”;
const ourNames = ${myName} ${yourName}
;
~~~
The type of ourNames will be string.
What is the type of count in:
let count;
count = 10;
Any
What is the type of result in:
function addTwo(a) { return a + 2; } const result = addTwo(4);
any
What is the type of result in:
function addTwo(a =1) { return a + 2; } const result = addTwo(4);
number
What is the type of result in:
let result;
any
Will this yield any error?
If not what will be the type of result?
let result; result = "Math"; result = 18; result = true; result = new Date(2023, 1, 1);
No error. The type is any
What does the type:
{ [field: string]: any }
means ?
It’s an object whose property names are of type string, with property values of typeany.
What kind of type checking those Typescript do on the any type?
None
What is the type void?
The void type represents a function’s return type when it doesn’t return any data.
What are the type(s) that void can be?
undefined or null if the strictNullChecks compiler option is off.
Will this raise an error?
~~~
const items = [];
items.push(1);
items.push(“two”);
items.push(false);
console.log(items);
~~~
No. items is of type any.
Will this raise an error?
const items: Array<number> = []; items.push(1); items.push("two"); items.push(false);
Yes. The type of items is number trying to push a string “two” and a boolean false is not allowed.
Declare a const called items and assign it a generic array of numbers and set its content to 1,2,3 at initialisation.
const items: Array<number> = [1,2,3];
Use the square bracket notation to create a const variable called items that is assigned to an array of strings containing “one”, “two”, and”three”.
const items : string[] = ["one","two", "three"];
What will be the type of array?
const array = [1, 2, 3]; console.log(array);
number
What is items and what is items type in this sample?
function logItems(name, ...items) { console.log(name, items); }
items is an array of type any. This type of parameter preceded by … is called a rest parameter.
What is a tuple?
A tuple can be thought of as an array with a fixed number of elements.
Do tuple exist in Javascript ?
The tuple type doesn’t exist in JavaScript. The closest we have are arrays, but there is no way of enforcing the number of elements and each element’s type.
Is this a tuple? What’s the type inferred ?
const score = ["Math", 95];
No, the type is:
(string | number)[]
So, the array can hold more than two elements
How can we modify this code sample to make sure we have a tuple of with a string and number?
const score = ["Math", 95];
const score: [string,number] = ["Math", 95];
Add a label name and score on this tuple:
const score: [string, number] = ["Math", 95];
const score: [name:string, score:number] = ["Math", 95];
Declare a tuple const named score with 2 labeled elements. The name element which should be a string and the score element which should be a number.
const score: [name:string, score:number] = ["Math", 95];
Create an open ended tuple called myNumbers taking a string called name and an unlimited number of numbers.
const myNumbers: [name:string, ...numbers:number[]] = ["Math", 95,65,89]; //...number[] is a rest element.
What is the type returned in the following function?
const keepGoing = (message: string) => { while (true) { console.log(message); } };
The return type is never because this function never returns. That’s why it’s not returning void.
Name a common use for the never type?
To flag region of code that should never be reached. For instance, using this kind of function:
function unreacheable(never: never) {}
Typescript will raise an error if it detects that this code can be reached.
Create a function called unreachable that takes in a parameter of type never called never.
function unreacheable(never: never) {}
Will this function raise an error:
~~~
function add(a: unknown, b: unknown) {
return a + b;
}
~~~
Yes. Variables of type unknown can’t be added together.
Modifiy the body of this function not its signature so that we check that a and b are numbers and add them or return 0 if they are not numbers.
function add(a: unknown, b: unknown) { return a + b; }
function add(a: unknown, b: unknown) {
if (typeof a === “number” && typeof b === “number”) {
return a + b;
}
return 0;
}
In the following function what are the type of a and b on the line:
return a + b; ?
function add(a: unknown, b: unknown) { if (typeof a === "number" && typeof b === "number") { return a + b; } return 0; }
number
What are type guard?
The type guard allows TypeScript to adjust the types of unknown to some other type it can work with.
You can’t operate directly on variables of type unknown. We have to give TypeScript information to narrow the type so that it can be used.
Given this:
~~~
interface Person {
firstName: string;
surname: string;
contactType: “person”;
}
interface Organisation {
name: string;
contactType: “organisation”;
}
type Contact = Person | Organisation;
~~~
Create a isPerson function that will take a any parameter named person and checks that the person parameter is of type Person using a type predicate.
function isPerson(contact: Contact): contact is Person { return (contact as Person).firstName !== undefined; }
Will Typescript detect a problem with this code? If so what is the problem?
~~~
const today = new Date();
console.log(today.getWeekDay());
~~~
The Date constructor can be called with no parameters but the Date type doesn’t contain a getWeekDay method.
What is the return type of this function:
function logMessage(message: string) { return console.log(message); }
void
What are correct type annotations for creating an array of dates?
~~~
1. date[]
2. Array<date>
3. Date[]
4. Array<Date>
~~~</Date></date>
The correct answers are:
~~~
3. Date[]
4. Array<Date>
~~~</Date>
What will TypeScript infer the type of the people variable to be in the declaration below?let people = ["Paula", "Bob", "Sam"];
string[]
How can we strongly-type the messages rest parameter so that only string types can be passed?
function outputMessages(...messages) { messages.forEach(message => console.log(message)); }
function outputMessages(…messages: string[]) {
messages.forEach(message => console.log(message));
}
The following function calls and thirdPartyCalculation method that returns any. Modify this function to use the unknown type and add a type guard to narrow down the type of result to number and return the result. Return undefined if the result is not a number.
function doWork() { const result = thirdPartyCalculation(); return result + 1; }
function doWork() { const result: unknown = thirdPartyCalculation(); if (typeof result === "number") { return result + 1; } return undefined; }
What is the type of the invalid variable in the function below?
function outputMessage(message: string) { if (typeof message === "string") { console.log(message); } else { let invalid = message; console.error(invalid); } }
never
We have a variable that will hold a two-dimensional point. What is most appropriate type annotation for this?
[number, number] is the most appropriate because is accepts 2 numbers.
The any type isn’t appropriate because no type checking will occur on the variable. number[] isn’t ideal because the array will accept more than 2 numerical values. [number] will not work because it will only accept 1 numerical value.
Create an enum called Level with the names Debug, Info, Error
enum Level { Debug, Info, Error }
For the following enum what will be the output value at the console for Info ?
enum Level { Debug, Info, Error }
1
enums values are zero-based auto-incrementing numbers by default.
Will this generate an error?
enum Level { Debug, Info, Error } let level: Level; level = 5; console.log(level);
No, unfortunately, numeric enums accept any numeric value.
Set a string value for each level in the following enum:
enum Level { Debug, Info, Error }
enum Level { Debug = "Debug", Info = "Info", Error = "Error" }
Will this code generate an error:
enum Level { Debug = "Debug", Info = "Info", Error = "Error" } let level:Level; level = Level.Error; console.log(level); level = "Debug";
Yes. We can’t assign the enum value using the string value:level = "debug"
Will generate an error.
The proper assignment would be:level = Level.Debug;
Declare a const score with an object implicitly typed with a name “Math” and a score of 85
const score = { name: "Math", score: 85 };
Using the explicit object type annotations specify a let variable called variable that contains a member1 of type1 and a member2 of type2.
let variable: { member1: type1; member2: type2};
Declare a const score with an explicitly typed object with a name “Math” and a score of 85
const score: { name: string; score: number; } = { name: "Math", score: 85 }
Declare a const score with an explicitly typed object with a name “Math” and a optional score left empty.
const score: { name: string; score?: number; } = { name: "Math" }
What is a type alias?
A type alias is a name that refers to another type
Create a new type TypeAliasName based of an existing type called ExistingType.
type TypeAliasName = ExistingType;
Create a type alias for a string called FirstName
type FirstName = string;
Create a type alias for a number called PersonScore.
type PersonScore = number;
Can Type aliases be used for arrow functions?
Yes.type TypeAliasName = (paramName1: paramType1; ...) => ReturnType;
Create a type alias called Log that represents this function:
Create a type alias called Log that represents this function: const log = (message: string) => { console.log(message); };
type Log = (message: string) => void;
Add Log in a type annotation to the function:
~~~
Create a type alias called Log that represents this function:
const log = (message: string) => {
console.log(message);
};
///The type:type Log = (message: string) => void;
~~~
const log: Log = (message: string) => { console.log(message); }
Add an optional parameter called category to the following type:type Log = (message: string) => void;
type Log = ( message: string; category?: string ) => void;
Create a type alias called score for :{ name: string; score: number }
In:
const score: { name: string; score: number } = { name: "Math", score: 85, };
type Score = { name: string; score: number };
In type alias should you use , or ; to separate type member ?
It’s better to use ;
Add an optional boolean pass property to this type:
~~~
type Score = {
name: string;
score: number;
};
~~~
type Score = { name: string; score: number; pass?: boolean; };
Can method be declared on object type?
Yes
Add a method of type Log on this Score alias:
type Score = { name: string; score: number; pass?: boolean; };
type Score = { name: string; score: number; pass?: boolean; log: Log; };
Do interfaces exist in Javascript?
No.
What is the syntax to declare an interface ?
Use these to help you: TypeName,propertyName,PropertyType,methodName,paramName, ParamType, MethodReturnType
interface TypeName { propertyName: PropertyType; methodName: (paramName: ParamType) => MethodReturnType; }
Declare a ButtonProps interface with a text string property and a onClick method that takes no parameter and return void. Use the arrow notation for the method signature.
interface ButtonProps { text: string; onClick: () => void; }
Make the method onClick optional on the following interface:
~~~
interface ButtonProps {
text: string;
onClick: () => void;
}
~~~
interface ButtonProps { text: string; onClick?: () => void; }
Is it possible for an interface to inherit all the properties and methods of another interface?
Yes. Through the use of extends.
Declare an interfaceA that has all the properties and methods of another interface called interfaceB
interface InterfaceA extends InterfaceB { ... }
Can interface be used to represent functions ?
Yes. Using this syntax:
~~~
interface TypeName {
(paramName1: paramType1, …): ReturnType;
}
~~~
What is the syntax for an interface to represent a function? Use TypeName, paramName1, paramType1 and ReturnType to help you.
interface TypeName { (paramName1: paramType1, ...): ReturnType; }
Declare an interface called Log for the following const:
~~~
const log = (message: string) => {
console.log(message);
};
~~~
interface Log {
(message: string): void;
}
Given the interface Log:
~~~
interface Log {
(message: string): void;
}
~~~
and the const log:
const log = (message: string) => { console.log(message); };
add the type annotation to log.
const log: Log = (message: string) => { console.log(message); }
Is it legal in Typescript to create multiple interfaces with the same names?
Yes. Typescript will merge the declaration with the same name. It’s called declaration merging.
When can it be useful to use declaration merging?
Mostly when using third-party libraries.
What are union type ?
They are types that we can combine to create a new type. We use the pipe | operator for this. For example:type A_or_B_or_C = A | B | C;
Change the type of :let age: number | null;
so it can be undefined as well.
let age: number | null | undefined;
Create a type alias from :let age: number | null;
type Age = number | null;
Create a string literal union type called Fruit with possible values of:
Banana, Apple, or Pear
type Fruits = "Banana", "Apple", "Pear";
When are string literal union types useful?
When we need a more specific type than string.
Are string literal union type case sensitive?
Yes.
Can objects be unioned as well?
Yes. For example:type Actions = { type: "loading" } | { type: "loaded"; data: { name: string } };
What is an intersection type and how can we express it?
Intersection types combine existing types to form a new type. An intersection type will have all the members from the types that it is based on. Intersection types don’t just contain the common members from the types that it is based on, as you may first expect.
type A_and_B_and_C = A & B & C;
What is the symbol used to declare intersection type?
&
Create an intersection type called Contacts from these 2 types:
~~~
type Name = {
firstName: string;
lastName: string;
};
type PhoneNumber = {
landline: string;
mobile: string;
};
~~~
type Contact = Name & PhoneNumber;
What will be the type of kind in the intersected Field type ?
~~~
type BaseElement = {
name: string;
kind: “text” | “number” | “email”;
};
type TextInput = {
kind: “text”;
};
type Field = BaseElement & TextInput;
~~~
It will be “text” because the type of a common member of an intersection type is mathematically intersected.
What parameter can the type A_and_B accept?
type A = { doIt: (a: string) => void; }; type B = { doIt: (a: string, b: string) => void; }; type A_and_B = A & B;
Only a:string
Can an interface represent a type primitive like string?
No. Only TypeAlias can do this.
Can an interface represent a tuple ?
No. Only a Type alias can do this.
Create a type called Names that is a array of string.
Copy
type Names = string[];
Create an interface called Names that represents an array of string.
interface Names { [index: number]: string; }
It’s simpler to use a type alias for this…
Declare a type called Log that take a parameter message a string and return void.
type Log = (message: string) => void;
Declare an interface called Log that take a parameter message a string and return void.
interface Log { (message: string): void; }
It’s clearer with a type…
Can interface represent union types?
No
Declare a type and interface called Person with a name string and a score number.
type Person = { name: string; score: number; }; interface Person { name: string; score: number; }
Can both interface and type alias be used to composed objects?
Yes. Type alias can be composed with the & intersection. Interface can be composed with extends.
Can type alias componse interfaces and vice versa ?
Yes. For example with & (intersection):
~~~
type Name = {
firstName: string;
lastName: string;
};
interface PhoneNumber {
landline: string;
mobile: string;
}
type Contact = Name & PhoneNumber;
~~~
What will be the type of status:
~~~
type OrderStatus = “pending” | “completed”;
type DeliveryStatus = “completed” | “shipped”;
type Status = OrderStatus | DeliveryStatus;
~~~
Status will contain ‘pending’, ‘completed’, and ‘shipped’ because we take the union of the values in the OrderStatus and DeliveryStatus sets.
What will be the type of status:
~~~
type OrderStatus = “pending” | “completed”;
type DeliveryStatus = “completed” | “shipped”;
type Status = OrderStatus & DeliveryStatus;
~~~
The Status
type will just contain ‘completed’ because we take the values where the OrderStatus and DeliveryStatus sets intersect.
What values does the never type contain?
The never type doesn’t contain any values and can be thought of as an empty set.
What values does the unknown type contain?
The unknown contains all the possible values!
What will be the type of status on the if line ? And on the console.log line ?
~~~
function logStatus(status: string | null) {
if (status) {
console.log(status);
}
}
~~~
On the if line, the type of status is string | null.
On the console.log line, the type of status is string.
The type was narrowed to string since the if check if we have a string or a truthy value. null would be a falsy value.
Would this raise an error:
~~~
let jones: “Tom” | “Bob” = “Tom”;
let jane: string = “Jane”;
jane = jones;
~~~
No because jane is of type string, which is wider than ‘Tom’ | ‘Bob’.
Would this raise an error:
~~~
let jones: “Tom” | “Bob” = “Tom”;
let jane: string = “Jane”;
jones = janes;
~~~
Yes because the type of jones is ‘Tom’ | ‘Bob’ which is narrower than the type of jane which is string. In other words, string can’t fit into ‘Tom’ | ‘Bob’.