根据Redux的创建者的教程,我创建了一个名为configureStore的函数来为我的应用程序创建商店,如下所示。我在没有if / else子句的情况下编译的示例编译没有错误。但是,如果我使用if / else检查(我需要),那么它就不会编译说
index.tsx type 'void' is not assignable to type 'Store<any>'
为什么将代码置于if / else子句中会影响类型(以及如何使其正确编译)?
configureStore.tsx (不会编译 - 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 (编译时没有错误)
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();
答案 0 :(得分:1)
TypeScript 1.6 release notes州:
TypeScript 1.6引入了新的
.tsx
文件扩展名。这个扩展 做两件事:它在TypeScript文件中启用JSX,以及它 使new as运算符成为转换的默认方式(删除任何 JSX表达式和TypeScript前缀强制转换之间的歧义 运营商)。例如:
var x = <any> foo;
// is equivalent to:
var x = foo as any;
行中的类型广告<any>window
:
if ((<any>window).serverSidePersistence != true) {
因此,不会被解释为.tsx
文件中的强制转换,而是解释为jsx元素。使用新的类型转换语法时,您应该很高兴:
if ((window as any).serverSidePersistence != true) {