【问题标题】:How can I call a Typescript generic method with a dynamically determined generic type?如何使用动态确定的泛型类型调用 Typescript 泛型方法?
【发布时间】:2021-09-03 07:54:23
【问题描述】:

我使用以下代码收到此错误: 'realType' 指的是一个值,但在这里被用作一个类型。你是说'typeof realType'吗?(

class Quux{};
class Foo extends Quux{};
class Bar extends Quux{};

const quuxBundle: Record<string, typeof Quux> = {
  "Foo": Foo,
  "Bar": Bar
};  

function lookupQuuxType(typeName: string): typeof Quux | undefined {
  return quuxBundle[typeName];
}
function fetchQuux<T extends Quux() {
  const result = {} as T;
  console.log('result', typeof result);
  return result;
}

const realType = lookupQuuxType('Foo');
fetchQuux<realType>();

【问题讨论】:

  • 首先,您发送的代码甚至不是有效的语法(&lt;T extends Quux() { 应该是什么?),而且 Typescript 也是一个纯粹的编译时类型系统,它没有对运行时的影响。

标签: typescript generics


【解决方案1】:

你不能使用 const 作为类型,如果你想使用你的 const 的类型,你应该以这种方式使用它typeof realType

这是您的更新代码:

class Quux{};
class Foo extends Quux{};
class Bar extends Quux{};

const quuxBundle: Record<string, typeof Quux> = {
  "Foo": Foo,
  "Bar": Bar
};  

function lookupQuuxType(typeName: string): typeof Quux | undefined {
  return quuxBundle[typeName];
}
function fetchQuux<T extends Quux>() {
  const result = {} as T;
  console.log('result', typeof result);
  return result;
}

const realType = lookupQuuxType('Foo');
fetchQuux<typeof realType>();

【讨论】:

  • 仅仅添加 'typeof' 是不行的。
猜你喜欢
  • 1970-01-01
  • 2019-07-23
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 2011-02-18
  • 2021-06-18
  • 2011-05-18
相关资源
最近更新 更多