Typescript 中具有 Null 和 Nullable Object 声明的联合类型之间的区别

Difference between Union Types with Null and Nullable Object declaration in Typescript

我最近在一个更大的 angular 项目中发现了一些打字稿代码,它的对象声明中有一个 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 代码?

顺便说一句: 在 Javascript 这个:

myVariable: Number | null;
myVariable = "Hello World";

就好了。

我的重点是对象的可空性以及这些声明的不同之处

Is there any difference between these two declarations?

是的,特别是 with strict null checks. A property with a union type| 符号)需要与匹配其中一种类型的值一起出现。

一个optional property (declared with ?) is just that: Optional. The object isn't required to have it at all. Although that said, at the moment (at least), TypeScript treats prop?: X exactly like prop: X | undefined; see this issue helpfully pointed out by jcatz.

没有严格的空值检查,这没问题:

type A = {
    dataSource: Date | null
};
type B = {
    dataSource?: Date
};

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

With strict null checks,第二个错误:

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

类似地,如果没有严格的空检查,分配 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

差别很大。 ?修饰符实际上等同于| undefined

这些是完全等价的:

myVariable: FileSource | undefined;
mySecondVariable?: FileSource;