【问题标题】:Is it possible to use the name of a class as the key of a new type?是否可以使用类的名称作为新类型的键?
【发布时间】: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


【解决方案1】:

这是我现在实施的评论:

class Animal {
  static readonly NAME: string;
}

class Dog extends Animal {
  static readonly NAME = "dog";

  get name(): string {
    return "test";
  }
}

// Declare `T` as an Animal constructor that also has a NAME
declare const convert: <T extends { new (...args: any[]): Animal; NAME: string }, P = {}>(
  type: T,
  component: React.FC<P & Record<T["NAME"], InstanceType<T>>> // use the NAME and set it to an instance of the constructor
) => React.FC<P & Record<T["NAME"], InstanceType<T>>>;

const MyComponent = convert(Dog, ({ dog }) => { // now OK
  return <div>{dog.name}</div>; // 'dog' is now type Dog
});

Playground

【讨论】:

    猜你喜欢
    • 2017-04-30
    • 2019-10-13
    • 2014-03-18
    • 2021-08-04
    • 2017-02-22
    • 2018-06-22
    • 2017-05-06
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多