Skip to content

Commit

Permalink
Section 1: Exercise 02: Tree-mendous Mapped Types
Browse files Browse the repository at this point in the history
  • Loading branch information
simonplend committed Jun 4, 2024
1 parent 71507ea commit f8a5206
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 0 deletions.
4 changes: 4 additions & 0 deletions 01-composing-types/exercise-02/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Exercise 02: Tree-mendous Mapped Types

In this exercise we're going to use one object type to create
another object type. It's tree-mendously powerful!
49 changes: 49 additions & 0 deletions 01-composing-types/exercise-02/completed/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
type Tree = {
name: string;
height: number;
age: number;
};

type TreeDetails<Type> = {
[Key in keyof Type as `get${Capitalize<string & Key>}`]: () => Type[Key];
};

type OakTree = TreeDetails<Tree>;

const oakData: Tree = {
name: "Oak",
height: 20,
age: 100,
};

let oak: OakTree = {
getName: () => oakData.name,
getHeight: () => oakData.height,
getAge: () => oakData.age,
};

console.log(`Name: ${oak.getName()}`);
console.log(`Height: ${oak.getHeight()}`);
console.log(`Age: ${oak.getAge()}`);

// ----

type PartialTree<Type> = {
[Key in keyof Type]+?: Type[Key];
};

let partialOak: PartialTree<Tree> = {
name: "Oak",
};

console.log({ partialOak });

// ----

type TreeWithAge<Type extends number> = `Tree with age ${Type}`;

type OldTree = TreeWithAge<ReturnType<OakTree["getAge"]>>;

let oldOak: OldTree = `Tree with age ${oak.getAge()}`;

console.log(oldOak);
3 changes: 3 additions & 0 deletions 01-composing-types/exercise-02/completed/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "@total-typescript/tsconfig/tsc/no-dom/app"
}
15 changes: 15 additions & 0 deletions 01-composing-types/exercise-02/start/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const oakData = {
name: "Oak",
height: 20,
age: 100,
};

let oak = {
getName: () => oakData.name,
getHeight: () => oakData.height,
getAge: () => oakData.age,
};

console.log(`Name: ${oak.getName()}`);
console.log(`Height: ${oak.getHeight()}`);
console.log(`Age: ${oak.getAge()}`);

0 comments on commit f8a5206

Please sign in to comment.