字符串不可分配给 keyof Readonly<T> 打字稿

String is not assignable to keyof Readonly<T> typescript

我在使用打字稿将字符串分配到 React 组件状态时遇到问题

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,
};

在这种情况下,使用 'showAll' 初始分配过滤器应该没问题,但会在

下面抛出编译错误
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、react 15.5.4、redux 3.6 和 react-redux 5.0.5

谢谢

{filter: 'showAll'} 表达式的类型是 {filter: string},它比 state 的类型更宽。那是因为 string'showAll' | 'showActive' | 'showCompleted' 的更宽类型(超类型)(状态中 filter 属性 的类型)。看来您需要使用类型转换:

state = <MainSectionState>{filter: 'showAll'};