簡體   English   中英

是否可以具有具有不同值類型的交集類型?

[英]Is it possible to have an intersection type with different value types?

我正在嘗試編寫可用於初始化模擬對象的初始化對象類型。 我不想定義所有字段,因為我想重用這種類型。 我像這樣定義了自定義類型:

type InitObjType = { [key: string]: string } & { customKey?: Observable<boolean> };

function initializator(obj: InitObjType) {...}

如果我嘗試將 init 對象傳遞給initializator函數,如下所示:

const subject = new Subject<boolean>;

initializator({
  a: 'a',
  b: 'b',
  c: 'c',
  customKey: subject,
});

我收到錯誤:

error TS2345: Argument of type '{ a: string; b: string; c: string; customKey: Observable<boolean>; }' is not assignable to parameter of type 'InitObjType'.
  Type '{ a: string; b: string; c: string; customKey: Observable<boolean>; }' is not assignable to type '{ [key: string]: string; }'.
    Property 'customKey' is incompatible with index signature.
      Type 'Observable<boolean>' is not assignable to type 'string'.

我使用 TypeScript 3.5.3。

有什么想法為什么類型的交集不起作用?

提前致謝!

有關於索引類型很好地解釋了這里

聲明索引簽名基本上意味着所有顯式屬性也需要符合索引簽名。 在聲明類型時,使用交集類型來解決此問題確實有效 - 但您將無法創建對象。 github上也有一些關於這個的討論。

使用子類型

將索引簽名移動到這樣的子類型被認為是最佳實踐:

type InitObjType = { 
  customKey?: Observable<boolean>,
  additionalProperties: { [key: string]: string }
};

function initializator(obj: InitObjType) {...}

const subject = new Subject<boolean>;

initializator({
  customKey: subject,
  additionalProperties: {
    a: 'a',
    b: 'b',
    c: 'c',
  }
});

使用較少類型安全的選項

如果您絕對必須將附加屬性保持在同一級別,則必須使用類型安全性較低的方式。 通過更改索引簽名:

type InitObjType = { 
  customKey?: Observable<boolean>,
  [key: string]: string | Observable<boolean>
};

// Or even less type-safe with any

type InitObjType = { 
  customKey?: Observable<boolean>,
  [key: string]: any
};

或者在創建對象時通過類型轉換:

const subject = new Subject<boolean>;

initializator({
  a: 'a',
  b: 'b',
  c: 'c',
  customKey: subject,
} as any);

最后一個例子有一個有趣的副作用。 由於 TypeScript 只會阻礙您創建這種類型的對象(因此您必須將其強制轉換為 any),因此您仍然可以將該對象強制轉換回以再次獲得類型安全性(權衡是每次都必須將其鍵入)。

const subject = new Subject<boolean>;

initializator({
  a: 'a',
  b: 'b',
  c: 'c',
  customKey: subject,
} as any as InitObjType);

暫無
暫無

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

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