2017-10-06 2 views
1

최신 typescript 및 reactjs 버전을 함께 사용하며 확장 클래스 및 해당 인터페이스의 확장에 문제가 있습니다.확장 클래스의 인터페이스를 확장하는 방법

/// <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; 

여러 폼 요소에 대한

내가 같이 보이는 BaseComponent을 만들었습니다 (모두 같은 검증 방법이) 내 컴파일러 (및 IDE)는 새로운 state.somethingNew 및 props.required 속성에 몇 가지 문제를 보여줍니다. 나는 이것을 확장하는 방법을 모른다. BaseComponent에 NameFieldContainer의 인터페이스를 사용해야한다는 것을 어떻게 가르 칠 수 있습니까?

답변

1

Intersection Type을 사용하여 소품 및 주에 대한 기존 인터페이스를 확장 할 수 있습니다. 귀하의 BaseContainer

class BaseContainer<PP, SS> extends React.Component<P & PP, S & SS> { 

} 

과 같을 것이다 그리고 그 당신의 구체적인 구현 당신은 또한 상태 필드 (value?:string로 선언하여) 선택하지 않은 경우 명심해야

interface PExtended { 
    id: string 
    onChange: Function 
    error: string 
    required?: boolean 
} 

interface SExtended { 
    value: string 
    isValid: boolean 
    somethingNew: string 
} 

class NameFieldContainer extends BaseContainer<PExtended, SExtended> {...} 

을 사용 setState({})에 설정해야합니다.

+0

고맙습니다! – Khazl

관련 문제