Angular2 templates have safe operator (?.), but in component.ts (typescript 2.0). Safe navigation operator (!.) not work.
Angular2模板具有安全的运算符(?。),但在component.ts(typescript 2.0)中。安全导航操作员(!)无法正常工作。
Example:
例:
This TypeScript
这个TypeScript
if (a!.b!.c) { }
compiles to this JavaScript
编译到这个JavaScript
if (a.b.c) { }
But when I run it, I get the follow error:
但是当我运行它时,我得到以下错误:
Cannot read property 'b' of undefined
无法读取未定义的属性'b'
Is there any alternative to:
还有其他选择:
if (a && a.b && a.b.c) { }
?
?
3 个解决方案
#1
48
Currently there's no safe navigation operator in typescript (still in discussion).
目前在打字稿中没有安全的导航操作员(仍在讨论中)。
!.
is non-null assertion operator - it just saying to type checker that you're sure that a
is not null
or undefined
.
!是非空断言运算符 - 它只是说键入检查器您确定a不是null或未定义。
More info here
更多信息在这里
#2
#3
5
You can try to write custom function like that.
您可以尝试编写这样的自定义函数。
The main advantage of the approach is a type checking, and partial intellisense.
该方法的主要优点是类型检查和部分智能感知。
export function nullSafe<T,
K0 extends keyof T,
K1 extends keyof T[K0],
K2 extends keyof T[K0][K1],
K3 extends keyof T[K0][K1][K2],
K4 extends keyof T[K0][K1][K2][K3],
K5 extends keyof T[K0][K1][K2][K3][K4]>
(obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) {
let result: any = obj;
const keysCount = arguments.length - 1;
for (var i = 1; i <= keysCount; i++) {
if (result === null || result === undefined) return result;
result = result[arguments[i]];
}
return result;
}
And usage (supports up to 5 parameters and can be extended):
和用法(最多支持5个参数,可以扩展):
nullSafe(a, 'b', 'c');
Example on playground.
在操场上的例子。
#1
48
Currently there's no safe navigation operator in typescript (still in discussion).
目前在打字稿中没有安全的导航操作员(仍在讨论中)。
!.
is non-null assertion operator - it just saying to type checker that you're sure that a
is not null
or undefined
.
!是非空断言运算符 - 它只是说键入检查器您确定a不是null或未定义。
More info here
更多信息在这里
#2
11
Another alternative that uses an external library is _.has() from Lodash.
另一种使用外部库的替代方法是Lodash的_.has()。
E.g.
例如。
_.has(a, 'b.c')
is equal to
等于
(a && a.b && a.b.c)
#3
5
You can try to write custom function like that.
您可以尝试编写这样的自定义函数。
The main advantage of the approach is a type checking, and partial intellisense.
该方法的主要优点是类型检查和部分智能感知。
export function nullSafe<T,
K0 extends keyof T,
K1 extends keyof T[K0],
K2 extends keyof T[K0][K1],
K3 extends keyof T[K0][K1][K2],
K4 extends keyof T[K0][K1][K2][K3],
K5 extends keyof T[K0][K1][K2][K3][K4]>
(obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) {
let result: any = obj;
const keysCount = arguments.length - 1;
for (var i = 1; i <= keysCount; i++) {
if (result === null || result === undefined) return result;
result = result[arguments[i]];
}
return result;
}
And usage (supports up to 5 parameters and can be extended):
和用法(最多支持5个参数,可以扩展):
nullSafe(a, 'b', 'c');
Example on playground.
在操场上的例子。