简体   繁体   English

是否可以使用字符串值来引用 Typescript 中的类型

[英]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函数添加动态返回类型,以便在上面的示例中, companyemployee被编译器称为CompanyEmployee实例?

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 操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeScript可以参考自己的房产类型吗? - Is it possible to refer self property type in TypeScript? 在打字稿中实现带有类型参数的函数时是否可以引用类型 - is it possible to refer to a type when implementing a function with type parameters in typescript 在 TypeScript 中,是否可以将字符串传递给泛型,然后将其用作类型/接口的键? - In TypeScript, is it possible to pass in a string to a generic and then use it as a key of the type/interface? 是否可以在 Typescript 的条件类型结果字段中使用泛型参数值? - Is it possible to use generic parameter value in conditional type result field in Typescript? 在 TypeScript 中,是否可以将任何类型的值转换为自定义类型并在值不匹配时使用默认值? - In TypeScript, is it possible to convert a an any type value to a custom type and use a default value should the value not match? Typescript:: 在 object 中,使用键字符串计算其值类型 - Typescript :: in an object, use key string to compute its value type 我应该在TypeScript中使用字符串文字作为返回值的类型吗? - Should I use a string literal as a type of a returned value in TypeScript? 是否可以通过 Typescript 中的映射类型将文字对象中的值(不是键)作为文字而不是其类型(例如字符串)获取? - Is it possible to get the value (not key) in a literal object as a literal, not its type (such as string) via mapped type in Typescript? 在 TypeScript 中使用变量值作为类型 - Use variables value as a type in TypeScript "是否可以在 TypeScript 中输入检查字符串别名?" - Is it possible to type check String Aliases in TypeScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM