Skip to content

Commit

Permalink
2023-08-16T13:23:08.893Z
Browse files Browse the repository at this point in the history
  • Loading branch information
mattpocock committed Aug 16, 2023
1 parent 3cc018b commit fb92816
Show file tree
Hide file tree
Showing 2 changed files with 122 additions and 1 deletion.
62 changes: 61 additions & 1 deletion src/020-objects/065-common-keys-of-unions-of-objects.problem.ts
Original file line number Diff line number Diff line change
@@ -1 +1,61 @@
// UserQuery | PostQuery
import { expect, it } from "vitest";

type User = {
id: string;
name: string;
age: number;
imageId: string;
};

type Organisation = {
id: string;
name: string;
address: string;
imageId: string;
};

const getAvatarImage = (entity: unknown) => {
{
// Should not be able to access properties that are
// not common to both types

// @ts-expect-error
entity.age;

// @ts-expect-error
entity.address;
}

return {
url: `https://via.placeholder.com/${entity.imageId}`,
alt: `${entity.name} Avatar`,
};
};

it("Should work for a user", () => {
const result = getAvatarImage({
id: "1",
name: "John",
age: 20,
imageId: "abc123",
});

expect(result).toEqual({
url: "https://via.placeholder.com/abc123",
alt: "John Avatar",
});
});

it("Should work for an organisation", () => {
const result = getAvatarImage({
id: "1",
name: "Total TypeScript",
address: "1 Main Street",
imageId: "abc123",
});

expect(result).toEqual({
url: "https://via.placeholder.com/abc123",
alt: "Total TypeScript Avatar",
});
});
61 changes: 61 additions & 0 deletions src/020-objects/065-common-keys-of-unions-of-objects.solution.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { expect, it } from "vitest";

type User = {
id: string;
name: string;
age: number;
imageId: string;
};

type Organisation = {
id: string;
name: string;
address: string;
imageId: string;
};

const getAvatarImage = (entity: User | Organisation) => {
{
// Should not be able to access properties that are
// not common to both types

// @ts-expect-error
entity.age;

// @ts-expect-error
entity.address;
}

return {
url: `https://via.placeholder.com/${entity.imageId}`,
alt: `${entity.name} Avatar`,
};
};

it("Should work for a user", () => {
const result = getAvatarImage({
id: "1",
name: "John",
age: 20,
imageId: "abc123",
});

expect(result).toEqual({
url: "https://via.placeholder.com/abc123",
alt: "John Avatar",
});
});

it("Should work for an organisation", () => {
const result = getAvatarImage({
id: "1",
name: "Total TypeScript",
address: "1 Main Street",
imageId: "abc123",
});

expect(result).toEqual({
url: "https://via.placeholder.com/abc123",
alt: "Total TypeScript Avatar",
});
});

0 comments on commit fb92816

Please sign in to comment.