casting – Typescript: Index signature is missing in type

casting – Typescript: Index signature is missing in type

The problem is that when the type is inferred, then the type of o is:

{ dic: { a: number, b: number } }

Thats not the same as { dic: { [name: string]: number } }. Critically, with the top signature youre not allowed to do something like o.dic[x] = 1. With the 2nd signature you are.

They are equivalent types at runtime (indeed, theyre the exact same value), but a big part of TypeScripts safety comes from the fact that these arent the same, and that itll only let you treat an object as a dictionary if it knows its explicitly intended as one. This is what stops you accidentally reading and writing totally non-existent properties on objects.

The solution is to ensure TypeScript knows that its intended as a dictionary. That means:

  • Explicitly providing a type somewhere that tells it its a dictionary:

    let o: MyInterface

  • Asserting it to be a dictionary inline:

    let o = { dic: <{ [name: string]: number }> { a: 1, b: 2 } }

  • Ensuring its the initial type that TypeScript infers for you:

    foo({ dic: { a: 1, b: 2 } })

If theres a case where TypeScript thinks its a normal object with just two properties, and then you try to use it later as a dictionary, itll be unhappy.

TS wants us to define the type of the index. For example, to tell the compiler that you can index the object with any string, e.g. myObj[anyString], change:

interface myInterface {
  myVal: string;
}

to:

interface myInterface {
  [key: string]: string;
  myVal: string;
}

And you can now store any string value on any string index:

x[myVal] = hello world
x[any other string] = any other string

casting – Typescript: Index signature is missing in type

For me error was solved by using type instead of interface

This error can occur when function foo has type instead of interface for typing parameter like

type MyType {
   dic: { [name: string]: number }
} 

function foo(a: MyType) {}

But passed value typed with interface like

interface MyInterface {
    dic: { [name: string]: number }
}

const o: MyInterface = {
    dic: {
        a: 3,
        b: 5
    }
}

foo(o) // type error here

I just used

const o: MyType = {
    dic: {
        a: 3,
        b: 5
    }
}

foo(o) // it works

Leave a Reply

Your email address will not be published. Required fields are marked *