我在使用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
谢谢
答案 0 :(得分:0)
{filter: 'showAll'}
表达式的类型为{filter: string}
,其宽度为state
的类型。这是因为string
是'showAll' | 'showActive' | 'showCompleted'
(州内filter
属性的类型)的更宽类型(超类型)。您似乎需要使用类型转换:
state = <MainSectionState>{filter: 'showAll'};