相关疑难解决方法(0)

TypeScript 中的可选参数可以为 null 吗?

根据这篇文章,当在 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)

nullable undefined optional typescript

37
推荐指数
1
解决办法
2万
查看次数

错误TS2345:类型"菜单"的参数不能分配给类型的参数

美好的一天.我是使用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)

typescript angular

1
推荐指数
1
解决办法
1425
查看次数

标签 统计

typescript ×2

angular ×1

nullable ×1

optional ×1

undefined ×1