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:
- 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{}"?? - Why is this useful? It now seems like I have to explicitly say what values the function
makeUserhave to use? (such as the id number, firstname etc)