javascript - Typescript 访问嵌套条件类型

标签 javascript typescript

我正在尝试访问给定以下类型定义的嵌套类型 b 并且 a 不为空:

type Abc = {
  a: {
    b: number
  } | null
}

但是,以下代码会导致错误: 类型 '{ b: number; 上不存在属性 'b'; } | null'.ts(2339)

const test: Abc["a"]["b"] = 3;

最佳答案

您可以将其更改为:

const test: NonNullable<Abc["a"]>["b"] = 3;

虽然这有点拗口。您还可以考虑将其拆分为几个接口(interface),并直接引用内部接口(interface):

interface Thing {
  b: number
}

type Abc = {
  a: Thing | null
}

const test: Thing["b"] = 3;

关于javascript - Typescript 访问嵌套条件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64147236/

相关文章:

javascript - JSON 数据到表单字段

javascript - 构建 NodeJS 模块 - 变量和方法

javascript - 您可以使用 javascript 操作浏览器的 WebSocket 连接吗?

javascript - 从另一个数组中过滤出一个数组

javascript - 数组和可观察数组有什么区别?

typescript - 类型注释: How to inherit from a Mixin of several classes and preserve static methods?

typescript - 如何使用泛型缩小 TypeScript 联合类型

javascript - 带有 jQ​​uery 的 float 侧边栏

javascript - Marionette.js EmptyChildView

twitter-bootstrap - 如何在 Bootstrap 模式 Angular 4 中正确显示谷歌地图