【发布时间】:2022-10-25 02:42:38
【问题描述】:
我想使用类的名称(作为变量提供)作为包装组件的属性。但我不确定如何使用打字稿来做到这一点。
简而言之:对象的键名(字符串)将派生自类的名称。
这是一个例子:
class Animal {}
class Dog extends Animal {
get name():string {
return 'test';
}
}
//Then I'm looking to create a function with a type declaration like this
//don't worry about the implementation, the bit that matters is T.toString()..
var convert:<T extends Animal, P={}>(
type:T,
component:React.FC<P>,
)=> React.FC<P & {T.toString().toLowerCase():T}>;
//so that I can do this:
const MyComponent = convert<Dog>(Dog,({dog:Dog}) => {
//the converted component receives a 'dog' property of the type Dog
return <div>{dog.name}</div>;
}
这在打字稿中可能吗?我将如何声明转换函数?
【问题讨论】:
-
这是不可能的,但是如果您在类上声明一个静态只读属性,那么您可能会使其工作。
标签: reactjs typescript types