我正在编写一些TypeScript代码,以便在TypeScript Playground学习。但是,错误有时显示在变量和值中,但我不知道为什么。类型错误不应该显示在第7行和第8行的未定义中,而不是a1和a2中吗?
type Foo = any[][]
type Baz = any[]
type Bar = any;
declare const elAny: Bar;
const a1: Foo = undefined; // error displayed under a1
const a2: Baz = undefined; // error displayed under a2
const a3: Bar = undefined;
const b1: Foo = elAny;
const b2: Baz = elAny;
const b3: Bar = elAny;
const c1: Foo = [1, 2, 3]; // error displayed under 1, 2, 3
const c2: Baz = [1, 2, 3];
const c3: Bar = [1, 2, 3];
demo image
这里有一个TS Playgound链接
1条答案
按热度按时间46scxncf1#
错误来自类型
any[]
不可为空。要修复它,您可以:
1.例如,只需执行
const a2: Baz = [];
,将变量设置为数组1.使用
any[]|null
将其标记为可空1.使用
var?: type;
将变量标记为可空,通常用于类型声明,但不能用于此特定示例。您可以找到更多关于可空类型here的信息。
附言:我没有尝试所有的选项,也许有些需要更多的变化。