为什么TypeScript中显示的类型错误不同?

blpfk2vs  于 2023-03-19  发布在  TypeScript
关注(0)|答案(1)|浏览(96)

我正在编写一些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链接

46scxncf

46scxncf1#

错误来自类型any[]不可为空。
要修复它,您可以:
1.例如,只需执行const a2: Baz = [];,将变量设置为数组
1.使用any[]|null将其标记为可空
1.使用var?: type;将变量标记为可空,通常用于类型声明,但不能用于此特定示例。
您可以找到更多关于可空类型here的信息。
附言:我没有尝试所有的选项,也许有些需要更多的变化。

相关问题