根据这篇文章,在TypeScript中启用了严格的null检查后,除非使用联合类型显式地允许,否则无法将
null
或undefined
赋值给变量。// required value
let req: string;
req = "Something"; // OK
req = null; // Error
req = undefined; // Error
// nullable value
let nbl: string | null;
nbl = "Something"; // OK
nbl = null; // OK
nbl = undefined; // Error
但是在 TypeScript 的 可选值 中是否允许使用 null
?
但是在 TypeScript 的 可选值 中是否允许使用 null
?
// optional value
let opt?: string; // (actually invalid, as optional types cannot be used for variable declarations, but that's not the point, so imagine we are dealing with function parameters or something)
opt = "Something"; // OK
opt = null; // OK? Error?
opt = undefined; // OK
还是
opt?: string;
等同于
opt: string | undefined;
因此,不允许null
,就像Microsoft编码指南建议的一样吗?
tsconfig.js
中指定了"exactOptionalPropertyTypes": true
时,示例 #5 中不允许使用undefined
。 - Allon Guralnek