簡體   English   中英

在這個 TypeScript 示例中,如何解決“X 被簡化為‘never’,因為屬性‘Y’在某些成分中具有沖突類型”?

[英]How to resolve "X was reduced to 'never' because property 'Y' has conflicting types in some constituents" in this TypeScript example?

我有一個相當大的編譯器項目,我正在處理,並將相關的 TypeScript 部分復制到這個 TypeScript 游樂場(它有很多類型,我認為這可能是問題的一部分)。

頂部的 function 是這樣的,它會引發錯誤:

export function createNest<T extends Nest>(
  like: T,
  scope: SiteStepScopeType,
): NestType<T> {
  return {
    children: [],
    like,
    scope,
  }
}

它正在投擲:

Type '{ children: never[]; like: Nest; scope: SiteStepScopeType; }' is not assignable to type 'NestType<T>'.
  Type '{ children: never[]; like: Nest; scope: SiteStepScopeType; }' is not assignable to type 'never'.
    The intersection 'NestBaseType & { like: Nest.Assertion; } & { like: Nest.Bind; } & SiteModuleBaseType & { like: Nest.BookModule; } & { like: Nest.Boolean; } & { like: Nest.BorrowVariable; } & ... 31 more ... & { ...; }' was reduced to 'never' because property 'like' has conflicting types in some constituents.(2322)

基本上:

...被簡化為“從不”,因為屬性“like”在某些成分中具有沖突的類型

like檢查了Nest*類型,它們都有一個相關值,我看不出有什么可能是錯誤的。 是因為我的種類多嗎? 或者到底錯在哪里?

錯誤消息相當混亂,但問題是編譯器不理解Nest中的值之一不是NestMappingType類型的鍵的情況。 據我所知,沒有辦法指定這種關系,但是您可以通過在createNest中對T使用附加約束和類型斷言來通知編譯器發生了什么,就像這樣;

export function createNest<T extends keyof NestMappingType & Nest>(
  like: T,
  scope: SiteStepScopeType,
): NestType<T> {
  return {
    children: [],
    like,
    scope,
  } as NestType<T>
}

如果你願意,你也可以像這樣重新定義Nest ,而不是額外的類型約束:

enum NestMappingKey {
  Assertion = "nest-assertion",
  Bind = "nest-bind",
}

export type Nest = NestMappingKey & keyof NestMappingType;

暫無
暫無

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

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