Reactjs 如何在react中重用childContextTypes中的类型定义?

Reactjs 如何在react中重用childContextTypes中的类型定义?,reactjs,typescript,Reactjs,Typescript,我正在使用Typescript开发React,我想在组件中使用childContextTypes: import * as React from "react"; interface Props { foo: string; bar: string; } export class Parent extends React.Component<Props, {}> { constructor(props:Props, context:any) { sup

我正在使用
Typescript
开发
React
,我想在
组件中使用
childContextTypes

import * as React from "react";

interface Props {
  foo: string;
  bar: string;
}

export class Parent extends React.Component<Props, {}> {
    constructor(props:Props, context:any) {
      super(props, context);
    }

    static childContextTypes =  {
      foo: React.PropTypes.string.isRequired,
        bar: React.PropTypes.string.isRequired,
    }

    getChildContext() {
        return this.props;
    }

    render() {
        return <Child />
    }
}

class Child extends React.Component<{}, {}> {
    context: any;

    static contextTypes = {
      foo: React.PropTypes.string.isRequired,
        bar: React.PropTypes.string.isRequired
    }

    render() {
      return <div>Hello, {this.context.foo}, {this.context.bar}</div>;
    }
}
import*as React from“React”;
界面道具{
foo:string;
酒吧:字符串;
}
导出类父类扩展React.Component{
构造函数(props:props,context:any){
超级(道具、背景);
}
静态childContextTypes={
foo:React.PropTypes.string.isRequired,
bar:React.PropTypes.string.isRequired,
}
getChildContext(){
归还这个道具;
}
render(){
返回
}
}
子类扩展了React.Component{
背景:任何;
静态上下文类型={
foo:React.PropTypes.string.isRequired,
条形图:React.PropTypes.string.isRequired
}
render(){
返回Hello,{this.context.foo},{this.context.bar};
}
}
如您所见,我只想重用我所有的
道具
,但在
childContextTypes
中,我必须指定所有
childContextTypes
,我不能重用
道具
接口


我可以重用
道具吗?我为什么需要它?现在,我只有两个道具,但我可能有更多的道具在某些情况下,我不想重写它

MappedTypes新的typescript功能可能有助于重写相同的类型定义:@OzBob,本例中的“props”是一个typescript接口,而静态childContextProps处于运行时,一旦tsc将typescript文件转换为javascript,该接口就完全消失了,它只由IDE使用,仅此而已。虽然您在childContextProps上设置的类型似乎也在运行时附加(独立于tsc)。因此,不,您不能重用“道具”,因为在这种特殊情况下,您不能将编译时值与运行时值结合起来。