[英]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
?是否可以向
findOne
函数添加动态返回类型,以便在上面的示例中, company
和employee
被编译器称为Company
和Employee
实例?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.