根据这篇文章,当在 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
Run Code Online (Sandbox Code Playgroud)
但是在 TypeScript 中null允许在可选值中使用吗?
// optional value
let opt?: string; // (actually invalid, as optional types cannot be used for variable declarations, but that's …Run Code Online (Sandbox Code Playgroud) 美好的一天.我是使用VSCode的Type Script的新手.
获得以下错误:
error TS2345: Argument of type 'Menu' is not assignable to parameter of type '{ state: string; name: string; type: string; icon: string;
badge?: undefined; children?: undefine...'
Run Code Online (Sandbox Code Playgroud)
该代码:
import { Injectable } from '@angular/core';
export interface BadgeItem {
type: string;
value: string;
}
export interface ChildrenItems {
state: string;
name: string;
type?: string;
}
export interface Menu {
state: string;
name: string;
type: string;
icon: string;
badge?: BadgeItem[];
children?: ChildrenItems[];
}
const MENUITEMS = …Run Code Online (Sandbox Code Playgroud)