-
A Weekend In Fortrose
Some clips from a last minute trip up to the Black Isle for the weekend.
-
Tartine Croissants
I recently picked up a copy of the revised edition of
Tartine
by Elizabeth Prueitt and Chad Robertson. Iâve already got the excellentTartine Bread
,Tartine Number 3
andTartine All Day
books and have been looking forward to their latest release.My first big bake from the book was a batch of croissants. Iâve made the hybrid naturally leavened croissants from Tartine Bread and although I was happy with them at the time, I think they could have been better and I was also curious to try this simpler, purely yeasted rendition.
The making process did not go smoothly. I drove home with the dough halfway through the bulk rise and it exploded out of its cling film wrapping. Then as the butter laminated rolls of dough cooked, all that butter started melting. There was butter everywhere.
Despite all of this, when I eventually pulled them out of the grease-laden oven, I could not have been happier with the results.
-
Flattening Typescript Union Types
In this post I describe how to flatten a union of two objects into one single object - sort of like outer joining two database tables. Click here to jump straight to the type alias for that
Union Types
Union Types in Typescript are a powerful way to describe a value that could be one of two or more types. They are particularly useful in codebases that are transitioning from Javascript to Typescript, where one function may accept an input parameter that can be one of several different types.
Hereâs an example of that in action, taken from the Typescript docs:
/** * Takes a string and adds "padding" to the left. * If 'padding' is a string, then 'padding' is appended to the left side. * If 'padding' is a number, then that number of spaces is added to the left side. */ function padLeft(value: string, padding: string | number) { if (typeof padding === "number") { return Array(padding + 1).join(" ") + value; } if (typeof padding === "string") { return padding + value; } }
Coming to Typescript from a background of using Swift, I found myself rarely using union types. I preferred writing things that either used concrete types or generics. However, I recently discovered the
typeof
operator in Typescript and have been loving using it.Typeof
The
typeof
operator allows you to create a type alias for the type of any typescript variable. When I first read about this operator I was thinking âWhy would you want to do that?â. It wasnât until I was converting a large amount of Javascript code to Typescript that I saw the usefulness of it. Typescript is great at inferring the types of variables youâve written.typeof
allows you to pass around inferred types and in some cases that means that you can avoid writing types and interfaces yourself.Now, thatâs a lot of abstract information, how does that look in practice?
My favourite use of
typeof
has been in a codebase I work on where we build several âappsâ from one codebase. All of these apps have differentconstants.ts
files.typeof
andimport()
have been incredibly valuable in automatically generating types for these files that can be passed around the codebase.// app-one/constants.ts export const COOKIE_KEYS = { AUTH_TOKEN: âX-Auth-Tokenâ } export const CURRENCY = âUSDâ
// app-two/constants.ts export const COOKIE_KEYS = { AUTH_TOKEN: âAUTHENTICATION_TOKENâ, LOGIN_TOKEN: âX-Login-Tokenâ } export const CURRENCY = âGBPâ
// shared/constants.ts type AppOneConstants = typeof import(â../app-one/constantsâ) type AppTwoConstants = typeof import(â../app-two/constantsâ) type AppConstants = AppOneConstants | AppTwoConstants
// src/api/middleware/authenticationMiddleware.ts const authenticationMiddleware = (request: Request, constants: AppConstants) => { request.addHeader(constants.COOKIE_KEYS.AUTH_TOKEN, âsome-tokenâ) }
Without
typeof
usages, weâd have to write and maintain anAppConstants
interface that aligns to the constants files of each app. In addition to this, Typescriptâs inference system can often type things better than you as a developer can. For example, in the above code snippets, if you had written the type ofAppConstants
yourself, you might have saidCOOKIE_NAMES
has a property ofAUTH_TOKEN
that is astring
. However, the inferred type will tell you thatAUTH_TOKEN
isâX-Auth-Tokenâ | âAUTHENTICATION_TOKENâ
. This extra bit of context can be really useful.Type inference has uses in other contexts too. You could infer the type of an API response from a mock JSON file; or you could have varied
Storage
objects for a Web app versus a ReactNative app; any time that youâre having to write a lot of types with Typescript, itâs worth thinking if thereâs a way you can have that type inferred for you.Merging Union Types
Now, inferred types are great, but when you are saying something is the union of some inferred types, there will be cases where the two types donât share properties. In this case, only shared properties will be accessible on the union type, unless you add a type check to confirm which side of a union your instance comes from.
Take the following data structures of a Superhero and Teacher for example:
const spiderman = { pseudonym: 'Spiderman', height: 150, address: { id: 500, headquarters: 'Avengers HQ' }, photos: [{ id: 1, name: 'spidey.jpg' }, { id: 4, name: 'doc-oct.jpg' }, { id: 5, remoteUrl: 'https://www.spiderman.com/image1.jpeg' }] } const mrTilbury = { firstName: "Arthur", secondName: "Tilbury", height: 180, subject: "Art", address: { id: 1231, streetAddress1: '1 Cadbury Lane', city: 'Norfolk', postcode: 'N1 KE5', }, degree: { university: 'Glasgow', subject: 'History of Art' } } type Teacher = typeof mrTilbury type Superhero = typeof spiderman type Person = Superhero | Teacher
Now, as Teacher and Superhero both have a height property, I can access height on an instance of the union type no problem:
const getHeightDetails = (person: Person) => { const heightInCm = person.height // OK, as both Superhero and Teacher have height return heightInCm }
But what if we want to try and use the
subject
property on a teacher?const getSubject = (person: Person) => { return person.subject // Compile error! }
Annoyingly, although
Person
is a union of aSuperhero
and aTeacher
, we get a compiler error on trying to accessperson.subject
becauseSuperhero
does not contain a subject property. (I would rather typescript âflattenedâ these union types for you. Such that aPerson
had a property ofsubject
that wasstring | undefined
.)To handle this use case, Typescript offers a feature called âDiscriminating Union Typesâ. This technique involves you adding a constant property to each side of a union that acts as a unique identifier for that type in the union. You can also check if a property is âinâ the variable that you know is unique to one side of the union, e.g photos on Spider-Man. However, this value might change, or the Teacher type may later get photos and youâd have to update all usages of discriminating by photo to instead discriminate by another property.
interface Superhero { type: âPERSONâ ...(other person values) } interface Teacher { type: âTEACHERâ subject: string ...(other teacher values) } type Person = Teacher | Superhero const somePerson = { type: âTEACHERâ, subject: âMathsâ } as Person // Just using `as` for the example if (somePerson.type === âTEACHERâ) { console.log(somePerson.subject) // Valid! }
By checking the
type
(our discriminator) isTEACHER
, we can access all properties that are unique to a Teacher and not in Superhero. This is useful and allows us to access properties in only one side of a union. However, it can be annoying to add a discriminating value to your objects (sometimes not possible), and it also adds an unnecessary runtime cost.FlattenUnion
Now, the main point of this post. There is a way that we can generate a
Person
type that makes properties of both types in the union accessible, whilst maintaining type safety.// Converts a union of two types into an intersection // i.e. A | B -> A & B type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never; // Flattens two union types into a single type with optional values // i.e. FlattenUnion<{ a: number, c: number } | { b: string, c: number }> = { a?: number, b?: string, c: number } type FlattenUnion<T> = { [K in keyof UnionToIntersection<T>]: K extends keyof T ? T[K] extends any[] ? T[K] : T[K] extends object ? FlattenUnion<T[K]> : T[K] : UnionToIntersection<T>[K] | undefined } type Person = FlattenUnion<Teacher | Superhero>
(Note: this is using recursive types, a new feature of Typescript 3.7. Without recursive types, weâd have to write a âfiniteâ version of this calling FlattenUnion -> FlattenUnion2 -> FlattenUnion3 for each nested object in a union)
By doing this, we now have a type that allows us to safely access any property on either side of a union. Going way back to the example at the top, we can now access deeply nested properties without having to check if each nested object contains a value for a key.
type Person = Teacher | Superhero type SafePerson = FlattenUnion<Person> // Using discriminating union, we have to check a property to verify the type const getPhotoWithId = (person: Person, id: number) => { if ('photos' in person) { return person.photos.find(p => p.id === id) } return undefined } // Using FlattenUnion const getPhotoWithId = (person: SafePerson, id: number) => person.photos?.find(p => p.id === id)
(Note: this is using the new nested optional syntax in Typescript 3.7)
By using the FlattenUnion version, we donât have to inspect the property to verify our photos property exist. We can autocomplete all properties - something that doesnât work with the discriminated union version as only the keys on both sides of the union are suggested by Typescript.
So, how is this
FlattenUnion<T>
actually working?To break it down, we take a type T and call
K in keyof UnionToIntersection<T>
. A simplekeyof T
would only give us the set of keys that are in both sides of the union, whereas swapping the union for an intersection means that we get all keys, even if they are only in one side of the union.Now, for every key we say if that key is in
keyof T
(i.e. is this key in both sides of the union) then we want to use that value as is - it is not optional and we know it exists in both sides of the union. We want to say, take this value, and if it is an object, return the FlattenUnion of that object (the recursive part). However, before we can think about usingFlattenUnion
, we have one edge case to cover first - arrays in Javascript are objects. So, we say if the value is an array of any type, then leave it untouched. Else if the value is an object, recursively callFlattenUnion
on the object, otherwise leave the value as it is (it is a number, string etc).If the key isnât in
keyof T
, then we know the value is in only one side of the union, leave the value as is but add an| undefined
as we know that it is not in both sides of the union. -
Potato Sourdough
One of the many great foods that my mum makes is potato bread rolls. These are small rolls that we have alongside a meal, made from yeasted dough and either instant or normal mashed potato. They are light in texture and taste great.
I was keen to try and bring this idea to the sourdough bread that Iâve been making as of recent. I researched online to see if there were any recipes available for this sort of dough, but I couldnât see anything that exactly matched what I wanted - this was an open crumb and no visible pieces of potato. There were several recipes I found that were using real potatoes and mixing it in smoothly, however, the dough that they made was of low hydration, fast rise and a closed crumb. Similarly, I did find one recipe that matched those characteristics. But, it was one where you left in chunks of potato, which I wasnât keen for.
I eventually gave up searching and just thought Iâd wing it with a recipe. It turned out far better than I could have hoped, so I thought Iâd share it here. It makes for a brilliantly moist crumb and flavoursome crust.
Recipe
- 400g strong white flour
- 100g whole wheat flour
- 375g water
- 11g salt
- 110g levain
- 250g potatoes, peeled and chopped into large chunks
08:00 - Prepare Levain
Prepare a levain in the morning by mixing 60 of flour, 60g of warm water and 60g of sourdough starter. (You may need to adjust ratios and timing based on the temperature of your kitchen or liveliness of your starter)
17:00 - Mix Dough & Boil Potatoes
Mix 350g water with the flour - we will save the other 25g of water for after the autolyse. Leave to rest for 30 minutes, covered. Whilst that rests, boil 250g of potatoes for 8 minutes. Once they are soft, remove from the heat and mash. Leave the mashed potatoes to cool until the autolyse is done.
17:30 - Mix Final Ingredients
Add the mashed potatoes, 11g of salt and 110g of levain to the dough and mix well. I like to use the âslap and foldâ technique. Cover and leave in a warm place.
18:00 - First Fold
Using a wet hand, stretch and fold the dough over itself at each corner.
18:30 - Second Fold
Repeat the previous set of folds.
19:00 - Third Fold
Repeat for the final set of folds then leave the dough to bulk rise.
22:00 Pre-Shaping
By now the dough should show visible bubbles and have risen noticeably. Turn it out onto a counter top and lightly flour one side of it. Using a scraper, starting at the floured side of the dough, pull the scraper round the dough and then back towards itself, creating a ball shape. Leave it to bench rest on the counter top.
22:45 Shaping
The dough will have spread out by now. Flour the top of it and then use a scraper to loosen it from the counter in place. Using the scraper, flip the dough so that the floured side now sits on the counter. Stitch the dough into a tight ball and place in a proofing basket. Either leave the dough to proof for 1-2 hours or put it in the fridge overnight.
08:00 Baking
If you proof the dough overnight in the fridge, the time at which you bake the next day is pretty flexible.
Place a lidded pod into the oven and preheat to 240 degrees. After 45 minutes, remove the pot from the oven and the proofing loaf from the fridge. Turn the dough out into the pot and optionally score the dough with a sharp blade. Place it back into the oven for 25 minutes. After 25 minutes, remove the lid and continue to bake for another 15 minutes.
-
Muji Water Repellent Trainers
Recently whilst on holiday in Milan I stopped in at a Muji store to buy some trainers Iâd been looking at online. Iâve now had them for around a month and I thought Iâd lend my thoughts to any others browsing the internet for info on them.
I went for a white pair of these shoes, though the black and the navy also looked great. Itâs a subtle off-white that I think is far nicer than any âpure whiteâ. If you have seen the 1970s Chuck Taylorâs that Converse put out recently, youâll know what to expect.
My only criticism of these shoes thus far is that they scuff really easily. At first I was trying to scrub off any marks from the front lip of the shoe. However, two weeks in I gave up and just let the dirt have its way.
They say the shoes are water repellent but I donât think youâll ever see that in effect or see its benefits. This repellency does not apply to the small pieces of dirt that shoes pick up day to day, and it is this that you will notice.
Iâve had no issues in particular with comfort, these feel as comfortable as any Converse that Iâve had in the past.
Speaking of Converse though, these shoes are a bargain. They retail for ÂŁ25 - the equivalent Chuck Taylors are ÂŁ65 - and I canât say Iâve any issues with their build quality. However, there is a question to be asked with how they can make shoes this cheap. It seems unlikely they can make these whilst being ethical and ecological but nonetheless, I donât imagine Converse do any better.
Iâve only had these shoes a short period of time, but I shall try and update this at some point to note how theyâve held up over time, and also just to add some more photos as Mujiâs website photos are as minimal in numbers as their products are in style.
-
Slap and Fold
Following my improvements of bread in my recent posts, I bought and read Trevor Jay Wilsonâs Open Crumb Mastery. The key takeaway I got from reading it was that I donât get nearly enough gluten development in my dough.
The lack of gluten development in my dough means that when stretched, the dough will burst rather than bubble. This is what is limiting the size of air pockets in my dough - or the âopenness of the crumbâ. This weak gluten is also a key factor in causing my loaves to spread out once I start to bake them. A stronger dough will hold its shape and stand tall, whereas a weaker one will spread out quickly.
I typically always used two things to develop the gluten in my dough. These were âtimeâ and sets of âstretch and foldsâ. I learnt this from âTartine Breadâ, âThe Perfect Loafâ and âFlour Water Salt Yeastâ. Itâs a really popular way to make bread just now. However, I canât seem to get the same results as others do with this method. Iâm imagining itâs related either to the temperature of my kitchen, the quality of gluten in the flour Iâm using, or the technique and frequency of my stretch and folds.
My new approach for developing gluten uses whatâs commonly called a âslap and foldâ technique. It involves you putting a wet dough on your countertop, picking it up by two sides, slapping the bottom edge down on the counter and quickly folding the bit you are holding down over the top of the dough. You then turn your hands 90 degrees and pick up the dough from the right and repeat the same motion to fold it in the opposite direction.
The results Iâve had with this have been brilliant. My dough feels stronger, shapes easier - with less flour - and holds its shape far better. Itâs even easier to score - giving me the most decorative loaves Iâve done yet.