0

I've seen a lot of questions about this but the answers always involve array literals, which is not helping me...

For example I've got a class like

interface Foo {
   [key: string]: Bar;
}

And I'd love to be able to do something like

function getFooMap(myFoo: Foo): Map<string, Bar> {
    return new Map(myFoo)
}

But I get the error

TS2345: Argument of type 'Foo' is not assignable to parameter of type 'readonly (readonly [{}, {}])[]'.
Type 'Foo' is missing the following properties from type 'readonly (readonly [{}, {}])[]': length, concat, join, slice, and 16 more.

I've also tried defining the method signature as

Array<[string, string]

function getFooMap(myFoo: Array<[string, Bar]): Map<string, Bar> {
    return new Map(myFoo)
}

But then the problem is I can't cast Foo to Array<[string, Bar] for some reason.

The below code crystalizes it. I really think it should work, it clearly doesn't, but I can't figure out what the right way is.

export interface Foo {
    [key: string]: Bar
}

const myFoo: Foo = [
    {key: "key1", value: {}},
    {key: "key1", value: {}},
    {key: "key1", value: {}}
]

I get the error

TS2322: Type '{ key: string; value: {}; }' is not assignable to type 'Bar'.
  Object literal may only specify known properties, and 'key' does not exist in type 'Bar'.
StolenKitten
  • 337
  • 1
  • 10

0 Answers0