【发布时间】:2018-01-08 23:10:52
【问题描述】:
我是打字稿的新手,最近正在写一门课。不幸的是,我的编辑器(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;
}
}
如果我取消注释上面的检查,错误才会消失,但由于构造函数:
constructor() {
this.foo = "hello";
}
this.foo 不能是未定义的,如果流程正确或我错了,则不应首先出现错误?
为了解释我为什么使用这个表达式
foo: string | undefined;
这只是一个简化的例子。我实际上是在尝试使用具有可以未定义的 Map.get() 函数的 Map 类型。这里是 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;
}
这里是实际代码:
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[]) {
}
}
谁能向我解释为什么会发生这个错误以及实现 EventEmitter 类的正确方法是什么?
【问题讨论】:
标签: javascript class typescript ecmascript-6