coatesap
coatesap

Reputation: 11127

Is it possible to use a string value to refer to a type in Typescript

For instance, I have a series of interfaces that describe the entities in my system:

interface Company {
  name: string
}

interface Employee {
  firstName: string
  lastName: string
}

And I'd like a generic function to fetch these entities, where an interface name can be passed as a string value.

const company = findOne('Company', 1)
const employee = findOne('Employee', 2)

Is it possible to add a dynamic return type to the findOne function, so that in the example above, company and employee are known by the compiler as instances of Company and Employee?

Upvotes: 1

Views: 60

Answers (1)

In order to do that, you can create an interface map type and infer your first argument:

interface Company {
  name: string
}

interface Employee {
  firstName: string
  lastName: string
}

type InterfaceMap = {
  Company: Company,
  Employee: Employee,
}

function findOne<Name extends keyof InterfaceMap>(name: Name, num: number): InterfaceMap[Name] {
  return null as any
}

const company = findOne('Company', 1) //  Company
const employee = findOne('Employee', 2) //  Employee

Playground

Upvotes: 2

Related Questions