Now Reading
What the heck is a homomorphic mapped kind? · andrea simone costa

What the heck is a homomorphic mapped kind? · andrea simone costa

2024-01-06 05:58:44

Featured image

I bear in mind again within the day once I stumbled upon the time period homomorphic for the primary time within the good ol’ TypeScript handbook. Actually, the handbook’s clarification was a bit fuzzy to me.

After itemizing a few instance mapped sorts:

kind Nullable<T> =  null ;
kind Partial<T> = { [P in keyof T]?: T[P] };

The handbook continued by saying:

In these examples, the properties listing is keyof T and the ensuing kind is a few variant of T[P]. This can be a good template for any normal use of mapped sorts. That’s as a result of this type of transformation is homomorphic, which signifies that the mapping applies solely to properties of T and no others.

Instantly afterward, it claimed that even Choose<T, Okay extends keyof T> = { [P in K]: T[P]; } is homomorphic, whereas Report isn’t:

Readonly, Partial and Choose are homomorphic whereas Report isn’t. One clue that Report isn’t homomorphic is that it doesn’t take an enter kind to repeat properties from. Non-homomorphic sorts are primarily creating new properties, [&mldr;].

The time period homomorphic is a little bit of a stretch from its math roots, however it’s principally saying that this type of mapped kind retains the unique kind’s construction intact. In reality, the TypeScript wiki states:

Mapped sorts declared as { [ K in keyof T ]: U } the place T is a kind parameter are often known as homomorphic mapped sorts, which signifies that the mapped kind is a construction preserving operate of T.

Wanting again, after getting cozy with the kind system, the handbook’s clarification makes extra sense now. However hey, there’s presently no up-to-date and full definition. The brand new handbook doesn’t even point out the time period homomorphic, however it does seem within the supply code.

I used to be simply bored with not having the complete image, so I opened up the compiler and tried to determine as soon as and for all what the heck a homomorphic mapped kind is.

getHomomorphicTypeVariable