必须先检查空值:
const matchLetter: RegExpMatchArray | null = points[0].match(/[a-zA-Z]/);
if (matchLetter) {
const direction: Tdirection = matchLetter[0];
}
如果Typescript不能自动识别
matchLetter
值已被选中,然后使其显式:
const matchLetter: RegExpMatchArray | null = points[0].match(/[a-zA-Z]/);
if (matchLetter) {
const direction: Tdirection = matchLetter![0] as Tdirection;
}
尾随者
!
是所谓的
non-null-assertion-operator
这使得可以为空的变量此时将包含一个值。如果我们有
type guard
在进入之前
火柴信
. 但我也看到过这样的案例,打字机的线头还在抱怨。
上的错误
direction
很清楚,因为您正在尝试将泛型字符串分配给字符串枚举。我把上面的代码改成了
as
铸造以使绒布安静下来。
一旦你改变了
方向
任务,您还需要更改
operations
结尾处的表达式:
var direction: Tdirection | undefined;
if (matchLetter) {
direction = matchLetter[0] as Tdirection;
}
if (direction) {
console.log(operations[direction](1, { x: 0, y: 0 }));
}