[英]Typescript - type 'string' can't be used to index type
I'm using Vue.js with TypeScript and have run into some errors when using dynamic object keys.我将 Vue.js 与 TypeScript 一起使用,并且在使用动态 object 密钥时遇到了一些错误。 Here is my function:
这是我的 function:
methods: {
interface ResetStateItems {
selected: WebspaceBackupArtifactExtended[];
selectedDirectory: string;
artifacts: WebspaceBackupArtifactExtended[];
isLoadingDirectory: boolean;
restoreComplete: boolean;
isProcessingBackupRestore: boolean;
}
resetPage() {
const resetStateItems: ResetStateItems = {
selected: [],
selectedDirectory: '/',
artifacts: [],
isLoadingDirectory: false,
restoreComplete: false,
isProcessingBackupRestore: false,
};
Object.keys(resetStateItems).forEach((stateItem: string) => {
this[stateItem as keyof resetStateItems] = resetStateItems[stateItem];
});
this.getWebspaceBackupByWebspaceIdAndId();
},
Here are the errors that I get:以下是我得到的错误:
ERROR in /app/src/views/BackupAndRestore/BackupAndRestoreWebspaceBackup.vue(484,9):
my-project | 484:9 Type 'any' is not assignable to type 'never'.
my-project | 482 |
my-project | 483 | Object.keys(resetStateItems).forEach((stateItem: string) => {
my-project | > 484 | this[stateItem as keyof ResetStateItems] = resetStateItems[stateItem];
my-project | | ^
my-project | 485 | });
my-project | 486 | this.getWebspaceBackupByWebspaceIdAndId();
my-project | 487 | },
ERROR in /app/src/views/BackupAndRestore/BackupAndRestoreWebspaceBackup.vue(484,52):
> my-project | 484:52 Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ResetStateItems'.
> my-project | No index signature with a parameter of type 'string' was found on type 'ResetStateItems'.
> my-project | 482 |
> my-project | 483 | Object.keys(resetStateItems).forEach((stateItem: string) => {
> my-project | > 484 | this[stateItem as keyof ResetStateItems] = resetStateItems[stateItem];
> my-project | | ^
> my-project | 485 | });
> my-project | 486 | this.getWebspaceBackupByWebspaceIdAndId();
> my-project | 487 | },
I'm not entirely sure what the issue is as I have defined the interface ResetStateItems
and thought I could just use keyof
to make it work?我不完全确定问题是什么,因为我已经定义了接口
ResetStateItems
并认为我可以使用keyof
使其工作?
Instead of using the variable name with the keyof
statement, use the interface name:不要在
keyof
语句中使用变量名,而是使用接口名:
this[stateItem as keyof ResetStateItems] = resetStateItems[stateItem];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.