这是 TypeScript 操场中一个可重现的示例,以我的问题为基础。
我收到代码的 TypeScript 错误router[trimmedPath]
:
错误:(63, 14) TS7053:元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“Router”类型。在类型“路由器”上找不到带有“字符串”类型参数的索引签名。
trimmedPath
来自 HTTP 请求并且可以是任何内容,因此它被输入为字符串。在上面的代码中,我只是调用router[trimmedPath]
,因为如果trimmedPath
不是router
对象上的东西,我会处理这种情况。
但是我该如何处理呢?我应该告诉 TS 忽略那条线吗?
鉴于以下定义:
interface Handlers {
users: Function,
notFound: Function,
}
const handlers: Handlers = {
users: () => {},
notFound: () => {}
}
我可能会创建一个Router
带有索引签名的接口,以便编译器知道router
可能具有string
包含其他Function
值的任意键控属性。为了保持严格的空/未定义安全,此索引签名的值类型应为Function | undefined
:
interface Router {
users: Function,
[otherPossibleKeys: string]: Function | undefined;
}
const router: Router = {
users: handlers.users
}
然后你可以毫无错误地使用它:
const trimmedPath: string = "somethingcomingfromrequest";
const chosenHandler =
typeof router[trimmedPath] !== "undefined"
? router[trimmedPath]
: handlers.notFound;
但是有一个皱纹:注意,chosenHandler
推断为Function | undefined
。这是因为即使router[trimmedPath]
已经明确检查,使用非文字索引(trimmedPath
is of type string
)的括号符号访问也不会充当类型保护,因此router[trimmedPath]
之后仍被考虑Function | undefined
。(这个问题被认为是一个错误或设计限制;它很容易修复,但编译器性能会受到影响)。
但是请记住,有一个在运行时工作相同但类型正确的构造:
const definedHandler = router[trimmedPath] || handlers.notFound;
这作品,因为Function
是truthy和undefined
是falsy,由于x || y
计算结果为x
,如果x
是truthy和y
否则,definedHandler
肯定会Function
。
所以这就是我的建议。希望有所帮助;祝你好运!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句