【问题标题】:String is not assignable to keyof Readonly<T> typescript字符串不可分配给 keyof Readonly<T> 打字稿
【发布时间】:2017-05-24 07:55:16
【问题描述】:

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

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

谢谢

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2021-09-22
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2019-04-10
    • 2016-10-25
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多