TypeScript Fundamentals: Function Basics
by Kwiz
Qs
7
Difficulty
Mid
Plays
0
Record
n/a
Description

This TypeScript quiz is a short one but includes some important questions regarding how TypeScript handles function signatures and return values!

Question Preview
Is the following type annotation for the function declaration valid?
function example(to: string): { foo: string; } {
  return {
    foo: `hello, ${to}`
  }
}
Question Preview
For both regular and arrow functions, return type annotations are placed in which position?
Question Preview
Return types for functions cannot be inferred by TypeScript
Question Preview
What is considered best practice regarding return type annotations for functions in TypeScript?
Question Preview
How would we annotate the type for the vals parameter in the following function?
function sum(...vals: /* ? */) {}

sum(3, 4, 5); 
Question Preview
TypeScript will complain about types in the following code
function contactPeople(
  method: "email" | "phone",
  ...people: (HasEmail | HasPhoneNumber)[]
): void {
  if (method === "email") {
    (people as HasEmail[]).forEach(sendEmail);
  } else {
    (people as HasPhoneNumber[]).forEach(sendTextMessage);
  }
}

contactPeople("email", { name: "foo", phone: 12345678 });
Question Preview
TypeScript allows us to define the value of "this" within a function declaration
interface Y {
  foo: string;
  bar: string;
}

function x(this: Y) {}