最近在研究TypeScript,结合React看了一下,发现了一段不是很好理解的类型定义,下面结合自己的理解来谈谈。 在types/react下,看到如下定义:
interface ComponentClass<P = {}, S = ComponentState> extends StaticLifecycle<P, S> {
new(props: P, context?: any): Component<P, S>;
propTypes?: WeakValidationMap<P>;
contextType?: Context<any>;
contextTypes?: ValidationMap<any>;
childContextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}
初一看,不知道怎么理解,经过一番查找官方文档,加上自己动手实践,理解如下:
1、这是定义了一个ComponentClass的接口,该接口继承了StaticLifecycle,接收两个泛型参数,P,S;
2、new(props: P, context?: any): Component<P, S>,这里是约束类的构造器(也就是constructor)的类型,接收两个参数,必传的props和可选参数context,返回值类型为Component;
3、propTypes,contextType等等属于类静态属性,使用static关键字定义
4、怎么用?给工厂函数调用,用来限制类的构造器类型
function createElement<P extends {}>(
type: ClassType<P, ClassicComponent<P, ComponentState>, ClassicComponentClass<P>>,
props?: ClassAttributes<ClassicComponent<P, ComponentState>> & P | null,
...children: ReactNode[]): CElement<P, ClassicComponent<P, ComponentState>>;
下面我仿造这种写法,结合官网的例子写了一段类似的代码
interface IClockConstructor {
new (hour: number, minute: number): IClockInterface;
PropType: string;
}
interface IClockInterface {
tick();
}
function createClock(Ctor: IClockConstructor, hour: number, minute: number): IClockInterface {
return new Ctor(hour, minute);
}
class DigitalClock implements IClockInterface {
public static PropType: 'test';
constructor(h: number, m: number) {
console.log(h, m);
}
public tick() {
console.log(this);
}
}
const digital = createClock(DigitalClock, 12, 17);
本文结束