String is not assignable to keyof Readonly<T> typescript

I have problem on assigning string into react component state using 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,
};

In this case it should be okay to initial assign filter with 'showAll', but throw compile error below

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"'.

What should i do with this problem?. i'm using typescript 2.3.2, react 15.5.4, redux 3.6, and react-redux 5.0.5

Thank you

Upvotes: 1

Views: 2138

Answers (1)

Kirill Dmitrenko
Kirill Dmitrenko

Reputation: 3649

Type of {filter: 'showAll'} expression is {filter: string}, which is wider that state's type. That's because string is a wider type (supertype) of 'showAll' | 'showActive' | 'showCompleted' (the type of filter property in the state). It seems that you'll need to use a type cast:

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

Upvotes: 1

Related Questions