Recent articles About

Compiling enterprise

Ivan Koshelev blog on software development

Articles for tags 'interfaces' Pragmatic uses of Typescript type system 01 My type of type [2019 February 22] Typescript, types, interfaces, duck typing

You may have heard, that TypeScripts type system has been prooven turing-complete . In layman’s terms this means you can write type definitions in such a way, that compiler will execute a simple program from just trying to compile them. A fascinating fact, but how is it useful in our daily work? It tells us, that TS type system is on a whole next level compared to what we are used to in Java and C#, and we should rethink our approach to it. In this article, we won't delve into the arcana of things like conditional types, but will concentrate on the often overlooked (especially by devs coming from the static typing world) practical uses of TS type system, that make daily life of a dev much easier.

Robert C. Martin of Clean Code fame once said, it would be nice if we could instruct compiler to use concrete types in Java only for their signature of abstractions, i.e., interfaces. Indeed, for 95% of enterprise code I work with, formal interface types serve as a technical detail, needed by the compiler only. Such case is easy to recognize: your interface has only 1 implementation (not counting testing mocks) and you don't have to ship/deploy this implementation separately (it is in the same DLL as interface, or the dll is separate, but always goes together). This is a clear sign:

  • this interface is driven by a single use case, which is fully reflected in single concrete implementation
  • only needed to teach compiler about proper dependency abstraction
  • you as a dev don't get anything out of it, worse yet, you are forced to duplicate member definitions
Ask yourself, how many interfaces in your application can be resolved by your IoC container automatically? Realizing this, I always wanted to be able to decorate my C# classes with a keyword or attribute, that would give me an automatic interface based on their concrete implementation and containing all their public members. Well, guess what we can do in TS?

class Foo {
    bar: number;
    baz() { console.log(this.bar); }
}

// An interface extends a class!
interface IFoo extends Foo { }

let foo = {} as IFoo;

let bar:number = foo.bar;
foo.baz();                  //type checks ok!

TS playground

And that is just the tip of the iceberg, real power comes in type!

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. May 2021 (1)
  2. March 2020 (1)
  3. August 2019 (1)
  4. July 2019 (1)
  5. May 2019 (1)
  6. February 2019 (1)
  7. October 2017 (1)
  8. August 2017 (3)
  9. July 2017 (3)
  10. May 2017 (3)

Elsewhere

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