1
type Config = {
    [key: string]: {
        client: string,
        connection: Object,
        models: Object,
    },
    def: string;
}

const config: Config = {
    def: `mysql`,
    mysql: {
        client: "mysql",
        connection: {
            host: 'host',
            port: 'port',
            // ...
        },
        models: {}
    }
}

throws:

Property 'def' of type 'string' is not assignable to 'string' index type '{ client: string; connection: Object; models: Object; }'.
Type '{ def: string; mysql: { client: string; connection: { host: string; port: string; }; models: {}; }; }' is not assignable to type 'Config'.
  Property 'def' is incompatible with index signature.
    Type 'string' is not assignable to type '{ client: string; connection: Object; models: Object; }'.

but I need to define type where def will be string type and any other value under any possible other key will be specific object. Any ideas how to achieve it?

Typescript playground with above example:

https://www.typescriptlang.org/play?#code/C4TwDgpgBAwg9gOwGYEsDmUC8UDeAoKQqAbQGsIQAuKAZ2ACcUE0Bda-IzqAYwBsUICYNTqNmAGgJdC3RAgjdgKRNQDyAIwBWC4JOmEAtnAAmEXjTVadeogF8bhU0hEMmaANx5bePLIR0eRFQ0anhkdCxcKUcIZygAAwMQGgBHXniHKCTU3nZorj4BIWoAImy0kszOP3lFZQQ8-S4ACzg6agByVroOqv0wOHphKA6Bod78poB6KagAOgXJuz7DEzMLXG9Ob1sgA

Edit:

I think I know what is happening here, why this is not covered, this comment on github describes it well:

https://github.com/microsoft/TypeScript/issues/17867#issuecomment-547940152

stopsopa
  • 408
  • 4
  • 20
  • There is no specific type in TypeScript which behaves the way you want; there are various workarounds. 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](https://stackoverflow.com/a/61434547/2887218). If I translate the code there to your example I get [this](https://tsplay.dev/mAv6PW), which shows the different possibilities. – jcalz Dec 09 '21 at 01:53
  • I would propose, that you write your `Config` as an union: `type Config = { [key: string]: {..} | { def: string; }` – scipper Dec 09 '21 at 07:24
  • Yes, error disappear but it actually allows me to define 'def' property as an object, which is not type safe. I'm generally stunned that this is not covered, and I've just started learning ts. That's awful – stopsopa Dec 09 '21 at 14:46

0 Answers0