如何在Typescript中正确覆盖泛型

时间:2018-10-22 07:20:07

标签: reactjs typescript

我们的祖先类具有一些属性(例如React)。

@RunWith(MockitoJUnitRunner.class)
public class TestSampleTest {

  @InjectMocks
  ChangerImpl changer;

  @Test(expected = NullPointerException.class)
  public void test1(){

    GroupProvider currentGroupAdm = mock(GroupProvider.class);
    doReturn(null).when(currentGroupAdm).getDocs();

    GroupProvider groupAdm = mock(GroupProvider.class);
    oReturn("sample2").when(groupAdm).getDocs();

    changer.hasDocsChangedRequired(currentGroupAdm, groupAdm);
  }

  @Test
  public void test2(){

    GroupProvider currentGroupAdm = mock(GroupProvider.class);
    doReturn("sample1").when(currentGroupAdm).getDocs();

    GroupProvider groupAdm = mock(GroupProvider.class);
    doReturn("sample2").when(groupAdm).getDocs();

    Assert.assertThat(changer.hasDocsChangedRequired(currentGroupAdm, groupAdm), is(true));
  }

  @Test
  public void test3(){

    GroupProvider currentGroupAdm = mock(GroupProvider.class);
    doReturn("sample1").when(currentGroupAdm).getDocs();

    GroupProvider groupAdm = mock(GroupProvider.class);
    doReturn("sample1").when(groupAdm).getDocs();

    Assert.assertThat(changer.hasDocsChangedRequired(currentGroupAdm, groupAdm), is(false));
  }

}

如何正确覆盖子组件?

export interface AncestorProps<T> {
    ...    
}

export class Ancestor<T> extends React.Component<AncestorProps<T>> {    
}

因为无法正常工作,所以我收到了此错误(提醒您,这是React):

  

[ts]键入'Readonly <{children ?: ReactNode; }>&   只读>>'没有属性   'someFunction',并且没有字符串索引签名。

Example

1 个答案:

答案 0 :(得分:1)

这些泛型的问题在于它们违反了function getLocalTime($date,$format){ global $mysqli; $time_offset = fetch_single_record('option_value','options',$mysqli,'option_name','local_time_offset'); $cmtDate = DateTime::createFromFormat('Y-m-d H:i:s.u', $date); $cmtDate->setTimeZone(new DateTimeZone($time_offset)); return $cmtDate->format($format); } 接受约定并将状态作为泛型参数的约定。父类不能像React.Component那样扩展,因为泛型参数不是Ancestor<DescendentProps<T>>中的props类型,而是其他类型。

一种解决方法是在子类中重新定义Ancestor类型:

props

使此层次结构可扩展的一种正确方法是始终遵循prop和state通用参数的约定。如果在export interface AncestorProps<T> {} export class Ancestor<T> extends React.Component<AncestorProps<T>> {} interface DescendentProps<T> extends AncestorProps<T> { someFunction: () => void; } export class Descendent<T> extends Ancestor<T> { props!: DescendentProps<T>; } 中不需要T参数,则应将其丢弃:

AncestorProps<T>