typescript - 使用 TypeScript 进行详尽检查,在对象中查找键

标签 typescript type-inference typechecking

假设我的服务器响应如下:“a”、“b”或“c”。这些映射到我的应用程序中的“alpha”、“beta”或“gamma”。如果我使用 JS,我会做以下翻译:

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

const lookUp = serverResponse => mapping[serverResponse];
我可以在 TypeScript 中做同样的事情。但是,假设我还希望保证万一服务器为“delta”添加“d”,我可以修改代码中的一个位置,并让 TS 帮助我使用其类型系统来指导我其余的重构。
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)
如果我将函数更改为使用 switch它不是在对象中查找,而是工作。但是switch陈述很笨拙。我也想双向转换,这使得对象非常容易使用,而不是 switch .
知道如何使上述代码在 TypeScript 中工作吗?

最佳答案

不确定详尽性检查,但在这种情况下 ServerResponsenever 不兼容.
试试这个中止函数的定义:

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

关于typescript - 使用 TypeScript 进行详尽检查,在对象中查找键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62681765/

相关文章:

haskell - 这是 Haskell 类型推理的实际应用,还是其他什么?

typescript - 如何键入检查内存中的 TypeScript 代码片段?

reactjs - React.FC<T> 和 Function() 之间的 React TypeScript 区别

typescript - TypeScript 中泛型子类型的推断

haskell - 如何理解 "ap = liftM2 id"的类型推断?

haskell - 类型类默认值中的类型注释会导致 "could not deduce"类型错误

javascript - 需要帮助在图像上传后在所选图像之间切换

typescript - Typescript 用户定义类型/对象的数组作为 Lit v2 中的属性

python - 在 Python 3.6 中运行时根据 Union 类型检查变量

javascript - 如何在运行时在 JavaScript 中生成类型检查?