5
interface Foo {
  bar: {};
  [key: string]: string;
}

// Property 'bar' of type '{}' is not assignable to string index type 'string'.

I'm trying to make property bar is Object and any other properties is string, how to define this without any?

xiaoxiyao
  • 89
  • 5
  • 1
    See [this question](https://stackoverflow.com/questions/61431397/how-to-define-typescript-type-as-a-dictionary-of-strings-but-with-one-numeric-i) and its answer for the issues surrounding such a "default" or "rest" index signature. Translating the code from that answer yields [this](https://tsplay.dev/wOaORm). Good luck! – jcalz Jun 08 '21 at 03:02

1 Answers1

2

This error is is not about the bar type is is about the dictionary you defined [key: string]: string;. Please check here.

But you can solve the problem like this:

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

type MainFooType = Foo & {
   bar: Object;
}

playground link

And the assignment can be:

const dictionary: { [key: string]: string } = { other: 'val2' };
let b: MainFooType = Object.assign({ bar: {} }, dictionary);

var f = b["bar"] // empty Object
var f1 = b["other"] // val2
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
  • it doesn't work if you actually want to assign to a variable of that type.[playgroud link](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGIHt3IN4ChnIDaA1hAJ4BcyAzmFKAOYC6Vt9IDA3LgL665gyABxQBZOKAzoAKsJQBeNJmQAyHPmQAjOFCoB5TQCsICMNz64ANhDDI4VcZMyyRyRXgLbdOHgBoN6GAAFtBUAORhvJxAA) – xiaoxiyao Jun 08 '21 at 07:06
  • You are in the wrong assignment with your dictionary. you have to use `Object.assign` . See [this](https://www.typescriptlang.org/play?#code/FASwdgLgpgTgZgQwMZQAQDED2nUG9iqoDaA1lAJ4BcqAzhDOAOYC61dDYjA3MAL7DAI5AA5oAsgnBZMAFRFoAvBmyoAZHgKoARghjUA8loBWUJBB79gSTGDqoAJiDMgbuqnmJl37Jq1r0mVF5UJVxUTAgAC1hqAHIANwQAGwAmWKCeJKgIbWoJKWw5URDUQxMzADoEGhoQRjAACjCdPTxg3gAaBycIFzA3AEoeYESYVDgSrSIAIhbp5lQAekXUKABbYSFS41MIEd1xgEZJmYjomHmllcTUoA) – Alireza Ahmadi Jun 08 '21 at 07:33
  • @xiaoxiyao I put the assignment part in my answer. – Alireza Ahmadi Jun 08 '21 at 07:37