Recent articles About

Compiling enterprise

Ivan Koshelev blog on software development

Articles for July 2019 Advanced uses of Typescript type system 01 From mapped types to compile-time type construction [2019 July 21] Typescript, types, type mapping This article continues exploration of typescript type system applications. Previous articles on pragmatic uses of ad-hoc typing and mapped types showcased type system usages for application developers. This one will go a bit deeper, and is more useful for library developers. Make sure you fully understand concepts explained previously.

Generic classes in C# and Java can be thought of as class templates, which let us use placeholders instead of certain types. What they don't allow is having generic property names. Typescript does not have such limitation and easily lets us do that:

export type MakeProp<TKey extends string , TType> = {
  [key in TKey]: TType
}

// MakeProp<'foo', number>
type equivalent1 = {
    foo: number;
}
TS playground

This does not look so impressive, after all, we could have written this type by hand just as easily. What we should know, however, is that we have passed they type-key barrier ( not a real term :-) ) - we managed to make type into a key and create an object shape using only other types. This means, we can use our 'MakeProp' type within other generic types in Typescript. With mapped and conditional types, this means we can construct much more complex types with our mappings.

continue reading
Ivan Koshelev photo

I'm passionate for anything that can be programed and automated to make life better for all of us.

Archives

  1. January 2023 (1)
  2. January 2022 (2)
  3. November 2021 (1)
  4. May 2021 (1)
  5. March 2020 (1)
  6. August 2019 (1)
  7. July 2019 (1)
  8. May 2019 (1)
  9. February 2019 (1)
  10. October 2017 (1)
  11. August 2017 (3)
  12. July 2017 (3)
  13. May 2017 (3)

Elsewhere

  1. GitHub@IKoshelev
  2. LinkedIn
  3. NuGet@IKoshelev
  4. NPM@IKoshelev