#Function Return Type Annotations??

2 messages · Page 1 of 1 (latest)

crystal ingot
#

https://www.totaltypescript.com/tutorials/beginners-typescript/beginner-s-typescript-section/function-return-type-annotations/exercise
Function Return Type Annotations

import { expect, it } from "vitest";

interface User {
  id: number;
  firstName: string;
  lastName: string;
  role: "admin" | "user" | "super-admin";
  posts: Array<Post>;
}

interface Post {
  id: number;
  title: string;
}

/**
 * How do we ensure that makeUser ALWAYS
 * returns a user?
 */
const makeUser = (): User => {
  return {
    id: 1,
    firstName: "Matt",
    lastName: "Pocock",
    role: "admin",
    posts: [],
  };
};

it("Should return a valid user", () => {
  const user = makeUser();

  expect(user.id).toBeTypeOf("number");
  expect(user.firstName).toBeTypeOf("string");
  expect(user.lastName).toBeTypeOf("string");
  expect(user.role).to.be.oneOf(["super-admin", "admin", "user"]);

  expect(user.posts[0].id).toBeTypeOf("number");
  expect(user.posts[0].title).toBeTypeOf("string");
});

I don't understand two things:

  1. How come we have to annotate the () (i.e. (): User => {) with a type to specify the return type of the function? I thought () => meant something like "this is a function that takes no input and returns whatever is in the {}"??
  2. Why is this useful? It now seems like I have to explicitly say what values the function makeUser have to use? (such as the id number, firstname etc)
inner vigil
#

(Answer I gave on Reactiflux for reference, if people don't want to repeat things I've already said)