import { createStore } from "redux";
import * as storage from "redux-storage";
const reducer = storage.reducer((state, action) => ({}));
const store = createStore(reducer, {});
Run Code Online (Sandbox Code Playgroud)
在strict启用打字稿的情况下使用上述代码时,我收到以下警告:
[ts] Argument of type 'Reducer<{}>' is not assignable to parameter of type 'Reducer<{}, AnyAction>'.
Types of parameters 'state' and 'state' are incompatible.
Type '{} | undefined' is not assignable to type '{}'.
Type 'undefined' is not assignable to type '{}'.
Run Code Online (Sandbox Code Playgroud)
我了解什么是 TS 严格模式,但我不明白为什么它将我的状态解释为潜在的 undefined
我可能做错了什么?或者我怎么能在不做一些懒惰的事情的情况下处理错误as any?
我试图strictNullChecks在角度4应用程序中实现.
我刚才说 "strictNullChecks": true 的tsconfig.json
当我运行应用程序时,ng serve我得到以下错误.
ERROR in [at-loader] ./node_modules/@angular/forms/src/model.d.ts:244:39
TS2459: Type '{ onlySelf?: boolean | undefined; emitEvent?: boolean |
undefined; } | undefined' has no property 'emitEvent' and no string index signature.
Run Code Online (Sandbox Code Playgroud)
出了什么问题?我们怎样才能
strictNullChecks在角4中实现?
在TypeScript中,如果启用了严格的null检查,我希望编译器阻止我向变量赋值null或undefined值,除非它允许null。
但是,数组访问似乎可以绕开此检查。
例:
let a: string[] = ["Hello"];
let s: string;
// 1) this produces an error, as expected
s = undefined
// 2) s is undefined here, too, but no error
s = a[3];
console.log(s);
Run Code Online (Sandbox Code Playgroud)
TypeScript Playground上的可运行版本(注意:必须在“选项”对话框中启用“严格的空检查”)。
这里发生了什么?
请考虑下面的代码以strictNullChecks打开:
var a: (number | null)[] = [0, 1, 2, 3, null, 4, 5, 6];
var b: { value: number; }[] = a.map(x => x != null && { value: x }).filter(Boolean);
Run Code Online (Sandbox Code Playgroud)
由于以下原因,它无法编译:
Type '(false | { value: number; })[]' is not assignable to type '{ value: number; }[]'.
Type 'false | { value: number; }' is not assignable to type '{ value: number; }'.
Type 'false' is not assignable to type '{ value: number; }'. …Run Code Online (Sandbox Code Playgroud) type Field = {test: {more: number} | null}
let fields: Field[] = [{test: {more: 55}}]
Run Code Online (Sandbox Code Playgroud)
无论类型保护如何,转译器都会抛出错误:
if (fields[0].test) {
fields[0].test.more = 55 // object is possibly null
}
Run Code Online (Sandbox Code Playgroud)
这里没有错误:
function f(field: Field) {
if (field.test) field.test.more = 15 // no error
}
Run Code Online (Sandbox Code Playgroud) 给定以下简单的类:
class Observer {
private subscribers: Map<string, Array<((data: any) => void)>> = new Map();
public subscribe(event: string, callback: (data: any) => void) {
if (!this.subscribers.has(event)) {
this.subscribers.set(event, []);
}
this.subscribers.get(event).push(callback); //tsc says: Object is possibly 'undefined'
}
}
Run Code Online (Sandbox Code Playgroud)
此外,在tsconfig.json中,标记strictNullChecks和strict被启用。
尽管subscribers已检查当前事件的键,但打字稿编译器会抱怨上面显示的错误消息(this.subscribers.get(event)可能未定义)。
如果我不是完全错误,在这种情况下this.subscribers.get(event)绝对不能undefined。
我如何摆脱该信息?