对于打字稿中的对象键,我想表达更严格的行为。
type UnionType = '1' | '2' | '3'
type TypeGuardedObject = { [key in UnionType]: number }
const exampleObject: TypeGuardedObject = {
'1': 1,
'2': 2,
'3': 3
}
// Is good because '1' is included in my type UnionType
const test1 = exampleObject['1']
// Should be bad because wrong key is a string, therefore, not necessary included
// in my type UnionType, but still passed the build successfully
const wrongKey: string = 'bad string'
const test2 = exampleObject[wrongKey]
有没有办法使我的第二个示例不通过打字稿构建?
谢谢
答案 0 :(得分:0)
为什么打字稿允许您索引对象与联合无关。在默认的编译器设置下,打字稿将任何对象视为具有索引属性。解决此问题的方法是启用编译器选项noImplicitAny
。这会在您的代码中浮出水面(我会争辩良好的错误和隐式键入的符号会破坏类型安全性,没有这种设置,您甚至可能不会意识到)。