I am new to TypeScript and facing a problem. I have a file with the extension .ts
where I store some helper functions. These functions are called using .call
so that the correct this
is referenced. However, in that file, each use of this
generates two errors:
'this' implicitly has type 'any' because it does not have a type annotation.
An outer value of 'this' is shadowed by this container.
Snippet from the component file:
<script lang="ts">
import { defineComponent } from "vue";
import { deleteTodo, getId, setEditId, toggleDone } from "./App.helpers";
import EditTodoDialog from "./components/EditTodoDialog.vue";
import TodoForm from "./components/TodoForm.vue";
import TodoTable from "./components/TodoTable.vue";
export default defineComponent({
components: { EditTodoDialog, TodoForm, TodoTable },
data() {
return {
addTodoInputValue: "" as string,
editTodoId: "" as string,
editTodoInputValue: "" as string,
todoArr: [] as Array,
};
},
methods: {
addTodo() {
if (this.addTodoInputValue) {
const id = getId();
const newTodo = {
handleDelete: () => deleteTodo.call(this, id),
handleSetEditId: () => setEditId.call(this, id),
handleToggleDone: () => toggleDone.call(this, id),
id,
isDone: false,
task: this.addTodoInputValue,
};
this.todoArr.push(newTodo);
this.addTodoInputValue = "";
}
},
closeDialog() {
this.editTodoId = "";
},
updateTodo() {
if (this.editTodoInputValue) {
const targetIndex = this.todoArr.findIndex(
({ id }) => id === this.editTodoId
);
this.todoArr[targetIndex].task = this.editTodoInputValue;
this.editTodoId = "";
this.editTodoInputValue = "";
}
},
},
name: "App",
});
</script>
Helper functions file:
export function deleteTodo(targetId: string) {
const targetIndex = this.todoArr.findIndex(
({ id }: { id: string }) => id === targetId
);
this.todoArr.splice(targetIndex, 1);
}
export function getId() {
return `${getRandomNumStr()}-${getRandomNumStr()}`;
}
export function getRandomNumStr() {
return Math.random().toString().slice(2);
}
export function setEditId(id: string) {
this.editTodoId = id;
}
export function toggleDone(targetId: string) {
const targetIndex = this.todoArr.findIndex(
({ id }: { id: string }) => id === targetId
);
const targetTodo = this.todoArr[targetIndex];
targetTodo.isDone = !targetTodo.isDone;
}