打字稿中带有null和可空对象声明的联合类型之间的区别

问题描述 投票:6回答:2

我最近在一个较大的角度项目中发现了一些打字稿代码,该项目的对象声明中包含Bitwise-OR / Pipe-Symbol。像这样:

dataSource: FileSource | null;

据我所知,它是类型为[[FileSource的对象,它也是nullable

dataSource = null; // Works dataSource = new FileSource... // Works dataSource = 32; // Error
我还发现,您可以使用

整个数据类型集

声明一个对象,如下所示:myVariable: number | string | null;
现在我的实际问题是:我也可以用

问号

声明一个对象作为可为空的符号。这两个声明之间有什么区别吗?myVariable: FileSource | null; mySecondVariable?: FileSource;
如果这两者之间没有区别,您会认为这是一种不好的做法,因为这在其他语言中并不常见,并且没有有效的JavaScript代码?

BTW:用Java语言编写:

myVariable: Number | null; myVariable = "Hello World";
可以。

我的重点是对象的可空性以及这些声明的区别

javascript angular typescript nullable
2个回答
6
投票
这两个声明之间有区别吗?

是,特别是with strict null checks。必须显示具有union type|符号)的属性,且其值必须与一种类型相匹配。

optional property(用?声明)只是:可选。完全不需要该对象。虽然如此,但至少在目前,TypeScript对待prop?: X的方式与prop: X | undefined完全相同;参见this issue有益地指出jcatz

Without严格的null检查,这很好:

type A = { dataSource: Date | null }; type B = { dataSource?: Date }; const a: A = { dataSource: null }; // Works const b: B = { dataSource: null }; // Also works

With严格的null检查,第二个错误:

type A = { dataSource: Date | null }; type B = { dataSource?: Date }; const a: A = { dataSource: null }; // Works const b: B = { dataSource: null }; // Error: Type 'null' is not assignable to type 'Date | undefined'.
Live Example in the Playground

类似地,如果没有严格的null检查,则分配undefined就可以了,但是对于联合检查,这是错误的。

type A = { dataSource: Date | null }; type B = { dataSource?: Date }; const a: A = { dataSource: undefined }; // Error: Type 'undefined' is not assignable to type 'Date | null'. const b: B = { dataSource: undefined }; // Works

Live Example in the Playground

2
投票
有很大的不同。 ?修饰符实际上等效于| undefined

这些完全等效:

myVariable: FileSource | undefined; mySecondVariable?: FileSource;

© www.soinside.com 2019 - 2024. All rights reserved.