如何扩展扩展类的接口
问题描述:
我将最新的typescript和reactjs版本一起使用,并且扩展类和扩展接口有问题。如何扩展扩展类的接口
几表单元素(都具有相同的验证方法),我创建了一个BaseComponent它看起来像这样:
/// <reference path="../typings/tsd.d.ts" />
import React = require('react');
interface P {
id: string
onChange: Function
error: string
}
interface S {
value: string
isValid: boolean
}
class BaseComponent extends React.Component<P, S> {
protected isValid(value) {
//do stuff
}
}
export default BaseComponent;
和从BaseComponent延长分量:
/// <reference path="../typings/tsd.d.ts" />
import React = require('react');
import BaseComponent from './baseComponent';
interface P {
id: string
onChange: Function
error: string
required?: boolean
}
interface S {
value: string
isValid: boolean
somethingNew: string
}
class NameFieldContainer extends BaseComponent {
constructor(props: any) {
super(props);
this.state = {
value: '',
isValid: false,
somethingNew: 'Foo'
};
this.aMethod();
}
protected aMethod() {
this.setState({somethingNew: 'Bar'});
}
public render() {
const somethingNew = this.state.somethingNew;
return (
<div>{somethingNew}</div>
);
}
export default NameFieldContainer;
现在我的编译器(和IDE)显示了新的state.somethingNew和props.required属性的一些问题。我不知道如何扩展它。我如何教BaseComponent他必须使用NameFieldContainer中的接口?
答
您可以使用Intersection Type来扩展道具和状态的现有接口。你BaseContainer
是这样
class BaseContainer<PP, SS> extends React.Component<P & PP, S & SS> {
}
和你的那个具体实施你会使用
interface PExtended {
id: string
onChange: Function
error: string
required?: boolean
}
interface SExtended {
value: string
isValid: boolean
somethingNew: string
}
class NameFieldContainer extends BaseContainer<PExtended, SExtended> {...}
你还必须记住,如果状态字段是不可选的(由宣称它作为value?:string
)你必须将它们设置为setState({})
。
作品,谢谢! – Khazl