The code below throws an error when attempting to spread an object after a null check. The error shows subtask as type “never” and then says I can’t use spread because it’s not an object even though I’m clearly checking that subtask exists before spreading it into a new object.
Any idea why this is happening and how I can resolve this error without resorting to removing type safety around the object?
type SubTaskFlow = 'Subtask1' | 'Subtask2'
type Status = 'NotComplete' | 'Complete'
type SubTask = {
flow: SubTaskFlow
status: Status
}
type Task = {
flow: 'Task1' | 'Task2'
subtasks: Array<SubTask>
status: Status
}
type Tasks = Array<Task>
const obj1:Task = {
flow: 'Task1' ,
subtasks: [{flow: 'Subtask1', status: 'NotComplete'}, {flow: 'Subtask1', status: 'NotComplete'}],
status: 'NotComplete'
}
const obj2:Task = {
flow: 'Task2',
subtasks: [{flow: 'Subtask1', status: 'NotComplete'}, {flow: 'Subtask2', status: 'NotComplete'}],
status: 'NotComplete'
}
const testFunc = (subtaskFlow: SubTaskFlow, status: Status) => {
const tasks = [obj1, obj2]
let subtask: SubTask | null = null
let subtaskToUpdateIndex: number = -1
let taskWithSubtaskToUpdateIndex: number = -1
tasks.forEach((task, taskIndex) => {
if (task.subtasks && task.subtasks.length) {
// iterate over the subtasks to check for match
task.subtasks.forEach((_subtask, subtaskIndex) => {
if (_subtask.flow === subtaskFlow) {
subtask = _subtask
subtaskToUpdateIndex = subtaskIndex
taskWithSubtaskToUpdateIndex = taskIndex
}
})
}
})
if(subtask){
const testsubtask = {...subtask}
}
}