typescript - 当通过括号访问键时,如何将键限制为 typescript 中定义的键

标签 typescript

我正在尝试在 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'.

Link to code

这就是您想要的错误:“类型上不存在属性”。

<小时/>

另一种可能性是使用类似 ESLINT 的 linter 以及类似 dot-notation 的规则。它根本不允许使用字符串文字作为属性索引。

<小时/>

恐怕我不知道还有什么针对单一对象类型的不那么激进的解决方案。您也许可以配置 linter,以便仅影响某些文件,这可能足够好,也可能不够好。

<小时/>

好的,希望有帮助;祝你好运!

关于typescript - 当通过括号访问键时,如何将键限制为 typescript 中定义的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60835080/

相关文章:

javascript - VueJS/Typescript - 找不到模块 './components/Navigation' 或其相应的类型声明

node.js - 使用 MSI 从 Linux 虚拟机中通过 Node 从 azure keyvault 获取 secret

javascript - Angular 6 : Unable to access js variable in template getting async data

javascript - 如何导入 Typescript 1.0 函数,如 node.js 需要带参数?

javascript - 如何使用属性对 Javascript 函数对象进行字符串化?

typescript - 在 TypeScript 中,是否有理由更喜欢 const foo : Type = {. ..} 或 const foo = { ... } 作为类型?

javascript - Angular - 多次使用的组件是否完全是自己创建的?

javascript - 比较对象数组和字符串数组

javascript - 为什么我的游戏中没有出现任何框?

javascript - 如何从 Angular 6 或 7 组件内的 LESS 文件访问 style.less 中的 LESS 变量?