字符串不能分配给keyof Readonly <t> typescript

时间:2017-05-24 07:55:17

标签: reactjs typescript redux react-redux typescript2.0

我在使用typescript

将字符串分配到反应组件状态时遇到问题
export default class MainSection extends React.Component<{}, MainSectionState> {
    state = {
        filter: 'showAll'
    };
}

interface MainSectionState {
    filter: keyof TodoFilter;
}

type TodoFilterCallback = (todo: Todo) => boolean;
type TodoFilter = { 
    showAll: TodoFilterCallback,
    showActive: TodoFilterCallback,
    showCompleted: TodoFilterCallback,
};

在这种情况下,应该可以使用&#39; showAll&#39;初始分配过滤器,但在下面抛出编译错误

error TS2415: Class 'MainSection' incorrectly extends base class 'Component<MainSectionProps, MainSectionState>'.
  Types of property 'state' are incompatible.
    Type '{ filter: string; }' is not assignable to type 'Readonly<MainSectionState>'.
      Types of property 'filter' are incompatible.
        Type 'string' is not assignable to type '"showAll" | "showActive" | "showCompleted"'.

我该怎么办这个问题?我使用的是typescript 2.3.2,反应15.5.4,redux 3.6和react-redux 5.0.5

谢谢

1 个答案:

答案 0 :(得分:0)

{filter: 'showAll'}表达式的类型为{filter: string},其宽度为state的类型。这是因为string'showAll' | 'showActive' | 'showCompleted'(州内filter属性的类型)的更宽类型(超类型)。您似乎需要使用类型转换:

state = <MainSectionState>{filter: 'showAll'};
相关问题