I'm using Vue.js with TypeScript and have run into some errors when using dynamic object keys. Here is my 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?
Instead of using the variable name with the keyof
statement, use the interface name:
this[stateItem as keyof ResetStateItems] = resetStateItems[stateItem];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.