[英]How to declare a nullable object literal variable in Typescript?
In typescript 2.2, when strictNullChecks option is true, how to declare a nullable object literal variable : 在打字稿2.2中,当strictNullChecks选项为true时,如何声明可为空的对象文字变量:
let myVar = { a: 1, b: 2 };
myVar = null; // Error can not assign null
The only ways I found is : 我发现的唯一方法是:
// Verbose
let myVar: { a: number; b: number; } | null = { a: 1, b: 2 };
// Bad, same as having no type
let myVar: any| null = { a: 1, b: 2 };
You can accomplish this by writing a nullable
utility function: 您可以通过编写
nullable
为nullable
实用程序函数来实现此目的:
const nullable = <T>(a: T) => a as T | null;
let myVar = nullable({ a: 1, b: 2 });
myVar = null; // Valid!
This does introduce an extra function call at variable initialization time, but likely this won't affect you much in most real world scenarios. 确实在变量初始化时引入了额外的函数调用,但是在大多数实际情况下,这可能不会对您造成太大影响。 The code is fairly clean, so I'm a fan of this solution.
代码相当干净,因此我是该解决方案的粉丝。
One other not so great way to do this would be the following: 另一种不是很好的方法是:
const fake = { a: 1, b: 2 };
let realVar: typeof fake | null = fake;
realVar = null;
The downsides are as follows: 缺点如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.