假设我的服务器响应如下:“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 中工作吗?
最佳答案
不确定详尽性检查,但在这种情况下 ServerResponse
与 never
不兼容.
试试这个中止函数的定义:
const shouldNeverReachHere = (x: unknown): never => {
throw new Error(`This value not exhaustively handled: ${x}`);
}
Playground
关于typescript - 使用 TypeScript 进行详尽检查,在对象中查找键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62681765/