簡體   English   中英

在 object 中查找密鑰,並使用 TypeScript 進行詳盡檢查

[英]Look-up a key in an object with exhaustiveness check with TypeScript

假設我的服務器響應以下內容:“a”、“b”或“c”。 這些 map 在我的應用程序中為“alpha”、“beta”或“gamma”。 如果我使用的是 JS,我會做以下翻譯:

const mapping = {
  a: 'alpha',
  b: 'beta',
  c: 'gamma'
}

const lookUp = serverResponse => mapping[serverResponse];

我可以在 TypeScript 中做同樣的事情。 但是,假設我還想要保證,如果服務器為 'delta' 添加了 'd',我可以在我的代碼中修改一個位置,並讓 TS 幫助我使用其類型系統來指導我重構的 rest。

type ServerResponse = 'a' | 'b' | 'c';
type ActualMeaning = 'alpha' | 'beta' | 'gamma';

const mapping: { [key in ServerResponse]: ActualMeaning } = {
  a: 'alpha',
  b: 'beta',
  c: 'gamma'
} as const;

const shouldNeverReachHere = (x: never): never => {
  throw new Error(`This value not exhaustively handled: ${x}`);
}

const lookup = (serverResponse: ServerResponse): ActualMeaning => {
  if (serverResponse in mapping) return mapping[serverResponse];
  return shouldNeverReachHere(serverResponse);
}

我希望由於mapping在編譯時是已知的(因為as const ),所以shouldNeverReachHere(serverResponse)的詳盡檢查會起作用。 但是,我收到該行的以下錯誤:

Argument of type '"a" | "b" | "c" is not assignable to parameter of type 'never'.
  Type '"a"' is not assignable to type 'never'. ts(2345)

如果我將 function 更改為使用switch而不是在 object 中查找,它可以工作。 但是switch語句很笨重。 我還想轉換兩種方式,這使得對象非常容易使用,而不是switch

知道如何使上述代碼在 TypeScript 中工作嗎?

不確定詳盡檢查,但在這種情況下ServerResponsenever不兼容。

試試這個中止 function 的定義:

const shouldNeverReachHere = (x: unknown): never => {
    throw new Error(`This value not exhaustively handled: ${x}`);
}

操場

暫無
暫無

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

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