Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

including if else clause creates type error

Following a tutorial by the creator of Redux, I created a function called configureStore to create the store for my app as you see below. The example where I compile without the if/else clause compiles without error. However, if I use the if/else check (which I need), then it doesn't compile saying

index.tsx type 'void' is not assignable to type 'Store<any>'

Why does putting the code inside an if/else clause affect the type (and how can I make it compile correctly)?

configureStore.tsx (won't compile -- index.tsx type 'void' is not assignable to type 'Store<any>')

export const configureStore = () => {
    const persistedState = loadState();
    let store: Store<any>;
    if ((<any>window).serverSidePersistence != true) {
        store = createStore(rootReducer, persistedState, applyMiddleware(thunk));
    } else {
        store = createStore(rootReducer, applyMiddleware(thunk)); 
    }
    return store;
}

configureStore.tsx (compiles without error)

export const configureStore = () => {
    const persistedState = loadState();
    let store: Store<any>;
    store = createStore(rootReducer, persistedState,applyMiddleware(thunk));
    return store;
}

index.tsx

 const store: Store<any> = configureStore();
like image 826
Leahcim Avatar asked Jun 21 '17 18:06

Leahcim


1 Answers

The TypeScript 1.6 release notes state:

TypeScript 1.6 introduces a new .tsx file extension. This extension does two things: it enables JSX inside of TypeScript files, and it makes the new as operator the default way to cast (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator). For example:

var x = <any> foo;
// is equivalent to:
var x = foo as any;

The type cast <any>window in the line:

if ((<any>window).serverSidePersistence != true) {

is thus not interpreted as a cast in a .tsx file, but as a jsx element. You should be good to go when using the new type casting syntax:

if ((window as any).serverSidePersistence != true) {
like image 142
Lodewijk Bogaards Avatar answered Sep 25 '22 17:09

Lodewijk Bogaards