'Can i use string array to describe interface of class?

i have a class like this:

interface Car {
  name: string
}

class CarCollection<T extends string> {
  [K: string]: Car;

  constructor(...names: T[]) {
    for (let name of names) {
      this[name as string] = { name }
    }
  }
}

now i can access properties like this:

const collection = new CarCollection('benz', 'tesla', 'toyota')

collection.benz      // Car
collection.tesla     // Car
collection.toyota    // Car
collection.a         // undefined
collection.b         // undefined
collection.undefined // undefined

i'm trying to limit the properties to just those three (benz, tesla, toyota).

i tired helper type like this:

type ICarCollection<T extends string> = {
  [K in T]: Car
}

now i have to write like this:

const collection: ICarCollection<'benz' | 'tesla' | 'toyota'> = new CarCollection('benz', 'tesla', 'toyota') as any

but i'm looking for any better way? thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source