作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在 typescript 中设置一个类型,因此当您尝试访问未通过这种访问类型exampleVar['test string']
定义的属性时,它会出错。
例如
type Account = {
accountInfo: accountInfo;
key: number;
}
type accountInfo = {
'Date Reported'?: string | null;
'Status': string | null;
}
const testAccount: Account = {
accountInfo: {},
key: 1
}
// This gives me a typescript error (which is expected)
testAccount.accountInfo.randomKey;
// This does not give me a typescript error (which is expected)
testAccount.accountInfo.Status;
// This does not give me a typescript error (when I want one)
testAccount.accountInfo['hello test'];
最佳答案
理想情况下,您应该使用 --strict
compiler option尽可能使用 TypeScript。默认情况下不会这样做以支持较旧的项目,这是不幸的,因为 TypeScript 的很多好处都来自这些严格的检查。无论如何,负责此操作的特定编译器选项将是 --noImplicitAny
。
编译器故意允许括号索引访问绕过正常的属性检查。但是,如果您执行这样的索引并且该属性中不存在该键,则编译器将将该属性的类型推断为 any
。并且 --noImplicitAny
会发出警告,因为您在没有注释的情况下得到了 any
:
testAccount.accountInfo['hello test'];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Element implicitly has an 'any' type because expression of type '"hello test"'
// can't be used to index type 'accountInfo'. Property 'hello test' does not exist
// on type 'accountInfo'.
这就是您想要的错误:“类型上不存在属性”。
<小时/>另一种可能性是使用类似 ESLINT 的 linter 以及类似 dot-notation
的规则。它根本不允许使用字符串文字作为属性索引。
恐怕我不知道还有什么针对单一对象类型的不那么激进的解决方案。您也许可以配置 linter,以便仅影响某些文件,这可能足够好,也可能不够好。
<小时/>好的,希望有帮助;祝你好运!
关于typescript - 当通过括号访问键时,如何将键限制为 typescript 中定义的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60835080/
我是一名优秀的程序员,十分优秀!