簡體   English   中英

打字稿訪問嵌套條件類型

[英]Typescript access nested conditional type

我正在嘗試根據以下類型定義訪問嵌套類型 b 並且 a 不為空:

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

但是,以下代碼會導致錯誤: Property 'b' does not exist on type '{ b: number; } | null'.ts(2339) Property 'b' does not exist on type '{ b: number; } | null'.ts(2339)

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

您可以將其更改為:

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

不過還是有點口無遮攔。 您也可以考慮將其拆分為幾個接口,並直接引用內部接口:

interface Thing {
  b: number
}

type Abc = {
  a: Thing | null
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM