blog podcast

The Curious Incident with the Type

Typescript is kind of talking to my past, as I used to be a .net developer. In the good old days I would write some reflection and generic stuff to try to squeeze the best out of .net 3.5. Well, that’s long in the past, and most of the things I’ve already forgotten. Anyway, now I had this case in Typescript where I wanted to create a string representation of my type based on properties that had a value. Right down the alley for what Javascript lets you do. Not so much type systems.

So what was then the issues? Well, from Typescripts point of view, I was trying to access random properties of my object, which could or also could not be properties of the class type that I had specified for that object. Typescript was not so happy. The error message was something like:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ ... }'.
  No index signature with a parameter of type 'string' was found on type

And the solution? Well, very explicitly telling the compiler that it is okay, see code underneath.

Code of the Day

This is the code as I wanted it:

    const attributeString = [...Object.keys(style)]
    .map((k) => { return {key: k, value: style[k]}})
    .filter(v => v.value !== undefined)
    .map(({key, value}) => `${key}:${value}`)
    .join(';');

This is the code that compiles:

    const attributeString = [...Object.keys(style)]
    .map((k) => { return {key: k, value: `${(style as {[key: string]: any})[k]}`}})
    .filter(v => v.value !== undefined)
    .map(({key, value}) => `${key}:${value}`)
    .join(';');