【发布时间】:2019-12-06 04:22:21
【问题描述】:
根据this article,当在TypeScript 中启用严格的空检查时,您不能将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
但是 null 在 TypeScript 的 optional 值中是否允许?
// 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's Coding guidelines 推荐的那样?
【问题讨论】:
标签: typescript undefined optional nullable