use*_*759 1 javascript class typescript ecmascript-6
我刚接触打字稿,最近正在写一门课。不幸的是,我的编辑器(Visual Studio Code)使我烦恼我无法理解的错误。它说:“对象(foo)可能是未定义的”。但是如何?
这是一个例子:
export class Foo {
foo: string | undefined;
constructor() {
this.foo = "hello";
}
lengthOfFoo() {
/*if (!this.foo) {
return;
}*/
let len = this.foo.length; // <- error: the object (foo) is possible undefined
return len;
}
}
Run Code Online (Sandbox Code Playgroud)
仅当我取消注释以上检查时,错误才会消失,但是由于构造函数:
constructor() {
this.foo = "hello";
}
Run Code Online (Sandbox Code Playgroud)
this.foo不能是不确定的,并且如果流程正确或我错了,那么错误应该不会首先出现。
为了解释为什么我使用这个表达式
foo: string | undefined;
Run Code Online (Sandbox Code Playgroud)
这只是一个简化的示例。我实际上是在尝试使用具有Map.get()函数(可能是未定义)的Map Type。这里是地图类型的声明:
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
readonly size: number;
}
Run Code Online (Sandbox Code Playgroud)
这里是实际的代码:
export default class EventEmitter {
listener: Map<string, Function[]> = new Map();
foo: string | undefined = "hello";
constructor() {
this.listener = new Map();
this.foo = "hello";
}
addListener(label: string, callback: Function) {
this.listener.has(label) || this.listener.set(label, []);
this.listener.get(label).push(callback); <- error: object is possible undefined
this.foo.length; // <- error: object is possible undefined
}
removeListener(label: string, callback: Function) {
}
emit(label: string, ...args: any[]) {
}
}
Run Code Online (Sandbox Code Playgroud)
谁能向我解释为什么会发生此错误,以及实现EventEmitter类的正确方法是什么?
this.foo不能是不确定的,并且如果流程正确或我错了,那么错误应该不会首先出现。
肯定是错的。有人可以这样写:
const f = new Foo();
f.foo = undefined;
f.lengthOfFoo();
Run Code Online (Sandbox Code Playgroud)