假设我有以下示例代码.这个共享组件的使用将有不同的有效nameprops ,这取决于组件的使用位置.是否可以动态导入TYPE_IMPORT,以便在不同的上下文中使用时导入适当的类型.

// example/import/path1.ts
export type TYPE_IMPORT = "foo" | "bar" | "testing1" | "testing2";
// example/import/path2.ts
export type TYPE_IMPORT = "pikachu" | "charmander" | "testing3" | "testing4";
import { TYPE_IMPORT } from 'example/import/path1';

interface IFooProps {
  name: TYPE_IMPORT;
}

export const FooComponent = (props: IFooProps ) => {
  const { name} = props;

  return (
    <svg>
      <use href={`#${name}`} />
    </svg>
  );
};

推荐答案

使用泛型将该类型委托给使用代码

interface ISvgProps<T> {
  name: T;
}

export const SvgComponent = <T extends string>({ name }: ISvgProps<T>) => (
  <svg>
    <use href={`#${name}`} />x
  </svg>
);

然后使用你想要的任何类型

import { TYPE_IMPORT as FooType } from 'example/import/path1';
import { TYPE_IMPORT as PokemonType } from 'example/import/path2';

const FooComponent = SvgComponent<FooType>;
const PokemonComponent = SvgComponent<PokemonType>;

// ...

return (
  <>
    <FooComponent name="foo" />
    <PokemonComponent name="pikachu" />
  </>
);

Typescript相关问答推荐

Angular 17 -如何在for循环内创建一些加载?

TypScript ' NoInfer '类型未按预期工作

React router 6.22.3不只是在生产模式下显示,为什么?

类型脚本强制泛型类型安全

为什么tsx不判断名称中有"—"的属性?'

Next.js错误:不变:页面未生成

使用TypeScrip根据(可选)属性推断结果类型

对未到达受保护路由的路由环境做出react

有没有可能产生输出T,它在视觉上省略了T中的一些键?

推断从其他类型派生的类型

如何编写在返回函数上分配了属性的类型安全泛型闭包

防止重复使用 Select 器重新渲染

tailwind css未被应用-react

使用Type脚本更新对象属性

如何使函数参数数组不相交?

任何导航器都未处理有效负载为";params";:{";roomId";:";...";}}的导航操作

无法使用prisma中的事务更新记录

Typescript泛型-键入对象时保持推理

可选通用映射器函数出错

带有 Select 器和映射器的Typescript 泛型