網站搜尋

typescript - 我如何在記錄的聯合類型上使用 `Pick` 或 `Omit`?


我有一個類型,是不同記錄類型的聯合,所有記錄都有相同的鍵,但每個記錄的某些鍵有不同的類型限制。我注意到當我對這個類型使用 Pick 或 Omit 時,我會失去一些類型檢查。

這裡有一個人為的例子:

type A = {
  type: 'a',
  content: 'a-content'
};

type B = {
  type: 'b',
  content: 'b-content'
}

type Full = {id: number} & (A|B);

// This is valid
const full: Full = {
  id: 1,
  type: 'a',
  content: 'a-content'
}

// This is correctly marked as a type error
const invalidFull: Full = {
  id: 1,
  type: 'a',
  content: 'b-content'
}

// This is not marked as a type error, even though the 'content' field doesn't match the 'type' field
const invalidFullPartial: Omit<Full, 'id'> = {
  type: 'a',
  content: 'b-content'
}

你會如何設置這個,以便你可以在 Full 類型上使用 Omit 或 Pick,並且仍然讓 TypeScript 確保 type 和 content 的類型相匹配?