Get Off My Lawn
Get Off My Lawn

Reputation: 36351

maped types: set key as an object

I am still trying to get my head around maped types, so what I am trying to achieve is a config of items that looks like this:

let config = {
    connA: {
      host: 'abc123',
      user: 'abc123',
      password: 'abc123',
      database: 'abc123',
    },
    connB: {
      host: 'abc123',
      user: 'abc123',
      password: 'abc123',
      database: 'abc123',
    }
}

I would like to setup a type for the keys connA, connB, and so on, where those could be anything.

export interface DatabaseConnection {
  host: string
  user: string
  password: string
  database: string
}

export type DatabaseConnections<T> = {
  [P in keyof T]: T[P]
}

So, when I use it, it would be something like this:

public static connect(config: DatabaseConnections<DatabaseConnection>) {
for (let db in config) {
  db.host
}

When I do this, it says that db is a string, and it should be an object (connA or connB in this example)

Upvotes: 0

Views: 68

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250396

From what I understand you are not looking for mapped types. You are looking for an index signature

export type DatabaseConnections<T> = {
  [name: string]: T
}

public static connect(config: DatabaseConnections<DatabaseConnection>) {
   for (let db in config) {
      config[db] // this will be of type T
   }
}

Upvotes: 1

Related Questions